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/Pythonlibrarymydb = 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 create a web application using Python and MySQL?
- How can I connect Python to a MySQL database?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python and MySQL?
- How can I connect to MySQL using Python?
- How do I connect Python with MySQL using XAMPP?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I convert data from a MySQL database to XML using Python?
- How do I connect to a MySQL database using XAMPP and Python?
- How do I use a WHERE query in Python and MySQL?
See more codes...