python-mysqlHow do I use Python and MySQL to execute multiple statements?
If you want to execute multiple statements in Python and MySQL, you can use the cursor.execute()
method. This method takes a single parameter, which is a string containing one or more SQL statements.
For example, the following code block will execute two SQL statements:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s); SELECT * FROM customers"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
This code will output the following:
(1, 'John', 'Highway 21')
The code consists of the following parts:
- Importing the
mysql.connector
module - Establishing a connection to the MySQL database
- Creating a cursor object
- Creating a string containing two SQL statements
- Executing the SQL statements
- Fetching the results
- Iterating through the results and printing each row
For more information, please refer to the MySQL Connector/Python documentation.
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How do I use Python to show the MySQL processlist?
- How do I access MySQL using Python?
- How do I connect Python with MySQL using XAMPP?
- How can I resolve the "no database selected" error when using Python and MySQL?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I decide between using Python MySQL and PyMySQL?
See more codes...