We'll delve into the process of inserting data into MySQL databases using Python. We'll cover everything from the basics of inserting single and multiple records to more advanced techniques such as inserting data from external sources.
Data insertion is the process of adding new records or rows of data into a database table. It’s a fundamental operation in database management and is essential for populating tables with the necessary information.
Inserting data into a database allows you to store and manage information for various purposes, such as analysis, reporting, and application functionality. Understanding how to insert data programmatically using Python provides flexibility and automation in managing your database.
The INSERT INTO
SQL statement is used to insert a single record into a table. It specifies the table name and the values to be inserted into each column.
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
Let’s insert a single record into a hypothetical “students” table with columns for id, name, and age.
import mysql.connector
# Connect to MySQL database
conn = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
# Create a cursor
cursor = conn.cursor()
# Execute INSERT INTO statement
cursor.execute("INSERT INTO students (name, age) VALUES ('Alice', 20)")
# Commit changes
conn.commit()
# Print confirmation message
print("Record inserted successfully")
# Close cursor and connection
cursor.close()
conn.close()
INSERT INTO
statement to insert a single record with the name “Alice” and age “20” into the “students” table.commit()
method.Sometimes, you may need to insert multiple records into a table simultaneously. This can be more efficient than inserting records one by one, especially when dealing with large datasets.
Let’s insert multiple records into the “students” table using a list of tuples containing the data for each record.
# Data for multiple records
data = [
('Bob', 22),
('Charlie', 21),
('David', 23)
]
# Execute INSERT INTO statement for each record
for record in data:
cursor.execute("INSERT INTO students (name, age) VALUES (%s, %s)", record)
# Commit changes
conn.commit()
# Print confirmation message
print("Multiple records inserted successfully")
INSERT INTO
statement for each record using a parameterized query to prevent SQL injection.In real-world scenarios, you may need to insert data into MySQL databases from external sources such as CSV files, Excel spreadsheets, or APIs. Python provides libraries and modules to facilitate this process.
Pandas is a powerful data manipulation library in Python that provides convenient functions for working with structured data, including reading data from various sources and inserting it into databases.
Let’s use Pandas to read data from a CSV file and insert it into a MySQL database.
import pandas as pd
import mysql.connector
# Read data from CSV file into a DataFrame
df = pd.read_csv("data.csv")
# Connect to MySQL database
conn = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
# Insert data into MySQL database
df.to_sql(name="students", con=conn, if_exists="append", index=False)
# Print confirmation message
print("Data inserted successfully")
# Close connection
conn.close()
to_sql()
function of Pandas to insert the data from the DataFrame into the “students” table in the MySQL database. The if_exists="append"
parameter ensures that existing data is not overwritten, and new records are added.We've covered the process of inserting data into MySQL databases using Python. We started with the basics of inserting single and multiple records and explored techniques for efficient data insertion. Happy Coding!❤️