python-mysqlHow do I perform multiple insert operations with Python and MySQL?
To perform multiple insert operations with Python and MySQL, you can use the executemany()
method of the MySQL cursor object. This method accepts a parameter which is a list of tuples, each tuple containing the data to be inserted into one row. The following example code shows how to use this method to insert multiple rows into a table:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('John', 'Highway 21'),
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
Output example
14 was inserted.
The code above:
- Imports the
mysql.connector
package. - Creates a connection to the MySQL database.
- Creates a cursor object.
- Defines the SQL query to be executed.
- Defines a list of tuples containing the data to be inserted.
- Executes the query using the
executemany()
method. - Commits the changes to the database.
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do I execute a query in MySQL using Python?
- How can I use Python and MySQL to generate a PDF?
- How can I use the Python MySQL API to interact with a MySQL database?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database using an Xserver?
- How do Python and MySQL compare to MariaDB?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I connect Python with MySQL using XAMPP?
See more codes...