python-mysqlHow can I execute multiple MySQL queries in Python?
You can execute multiple MySQL queries in Python using the MySQL Connector/Python
library.
Example code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Peter", "Lowstreet 4")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Output example
2 record inserted.
Code explanation
import mysql.connector
: imports theMySQL Connector/Python
librarymydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword")
: connects to the MySQL database using the provided credentialsmycursor = mydb.cursor()
: creates a cursor objectsql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
: creates a SQL query stringval = ("John", "Highway 21")
: creates a tuple containing the values to be inserted into the databasemycursor.execute(sql, val)
: executes the SQL query using the provided valuesmydb.commit()
: commits the changes to the databaseprint(mycursor.rowcount, "record inserted.")
: prints the number of records inserted
Helpful links
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How can I connect Python to a MySQL database?
- How do I use a SELECT statement in Python to query a MySQL database?
- How can I use multiple cursors in Python to interact with MySQL?
- How can I print the result of a MySQL query in Python?
- How can I use Python and MySQL to generate a PDF?
- How do I use Python to authenticate MySQL on Windows?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use a WHERE query in Python and MySQL?
- How can I use a MySQL variable in Python?
See more codes...