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 do I use Python to query MySQL with multiple conditions?
- How can I use Python and MySQL to create a login system?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to authenticate MySQL on Windows?
- How can I connect Python to a MySQL database using an Xserver?
- How can I use the "order by" statement in Python to sort data in a MySQL database?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I connect to a MySQL database using Python and MySQL Workbench?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
See more codes...