Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Mysql Insert in Python

Mysql Insert in Python

MySQL Insert in Python

In Python, you can insert data into a MySQL database using the mysql-connector-python library.


1. Install MySQL Connector

If you haven’t installed the MySQL connector, install it using:

pip install mysql-connector-python

2. Connect to MySQL Database

First, establish a connection to your MySQL database.

import mysql.connector# Connect to MySQL Databaseconn = mysql.connector.connect(    host="localhost",    user="root",    password="password",    database="mydatabase"  # Change to your database name)# Create a cursor objectcursor = conn.cursor()print("Connected to MySQL database successfully!")

3. Insert a Single Record

To insert a single row into a table:

# SQL query to insert datainsert_query = "INSERT INTO employees (name, age, department) VALUES (%s, %s, %s)"values = ("Alice", 30, "HR")# Execute the querycursor.execute(insert_query, values)conn.commit()  # Commit changes to the databaseprint("1 record inserted, ID:", cursor.lastrowid)

4. Insert Multiple Records

To insert multiple rows at once:

# List of tuples containing datavalues = [    ("Bob", 25, "IT"),    ("Charlie", 28, "Finance"),    ("Diana", 35, "Marketing")]# SQL queryinsert_query = "INSERT INTO employees (name, age, department) VALUES (%s, %s, %s)"# Execute query for multiple recordscursor.executemany(insert_query, values)conn.commit()print(cursor.rowcount, "records inserted.")

5. Verify Inserted Records

To check if the data was inserted successfully:

cursor.execute("SELECT * FROM employees")# Fetch all recordsrecords = cursor.fetchall()print("Employees List:")for row in records:    print(row)

6. Closing the Connection

Always close the database connection after completing operations.

cursor.close()conn.close()print("MySQL connection closed.")

Final Complete Code

import mysql.connector# Connect to MySQL Databaseconn = mysql.connector.connect(    host="localhost",    user="root",    password="password",    database="mydatabase")cursor = conn.cursor()# Insert Multiple Recordsinsert_query = "INSERT INTO employees (name, age, department) VALUES (%s, %s, %s)"values = [    ("Alice", 30, "HR"),    ("Bob", 25, "IT"),    ("Charlie", 28, "Finance"),    ("Diana", 35, "Marketing")]cursor.executemany(insert_query, values)conn.commit()print(cursor.rowcount, "records inserted.")# Verify Inserted Recordscursor.execute("SELECT * FROM employees")records = cursor.fetchall()print("Employees List:")for row in records:    print(row)# Close Connectioncursor.close()conn.close()

Summary

TaskSQL Query
Insert a single recordINSERT INTO employees (name, age, department) VALUES (%s, %s, %s)
Insert multiple recordsexecutemany() with multiple values
Verify inserted recordsSELECT * FROM employees
Commit changesconn.commit()

This is how you insert data into MySQL using Python! ?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql