python-mysqlHow can I insert data into a MySQL database using Python?
To insert data into a MySQL database using Python, you can use the mysql.connector
library. The following example code shows how to connect to a MySQL database, create a table, and insert data into the table.
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password"
)
# Create a cursor
mycursor = mydb.cursor()
# Create a table
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
# Insert data into the table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
# Commit the changes to the database
mydb.commit()
# Print the number of rows affected
print(mycursor.rowcount, "record inserted.")
Output example
1 record inserted.
Code explanation
- Import the
mysql.connector
library -import mysql.connector
- Connect to the database -
mydb = mysql.connector.connect(host="localhost", user="user", passwd="password")
- Create a cursor -
mycursor = mydb.cursor()
- Create a table -
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
- Insert data into the table -
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
- Execute the SQL query using the cursor -
mycursor.execute(sql, val)
- Commit the changes to the database -
mydb.commit()
Helpful links
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How do I use Python to authenticate MySQL on Windows?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I host a MySQL database using Python?
- How do I access MySQL using Python?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How can I use the Python MySQL API to interact with a MySQL database?
See more codes...