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 do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I use Python and MySQL to generate a PDF?
- How do I use Python to query MySQL with multiple conditions?
- How do I check the version of MySQL I am using with Python?
- How do I use a SELECT statement in Python to query a MySQL database?
- How do I execute a query in MySQL using Python?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
See more codes...