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 connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to connect to a MySQL database using XAMPP?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I connect to XAMPP MySQL using Python?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to fetch an associative array from a MySQL database?
See more codes...