python-mysqlHow do I execute a batch insert into a MySQL database using Python?
To execute a batch insert into a MySQL database using Python, you need to do the following:
- Establish a connection to the database:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
- Create a list of values to insert:
sql_values = [
('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')
]
- Create the SQL query:
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
- Execute the query using the
executemany()
method:
mycursor.executemany(sql, sql_values)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Output example
14 records inserted.
- Close the connection:
mycursor.close()
mydb.close()
Helpful links
More of Python Mysql
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use Python to query MySQL with multiple conditions?
- How can I set a timeout for a MySQL connection in Python?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I use the MySQL Connector in Python?
- How can I retrieve unread results from a MySQL database using Python?
- How can I use Python and MySQL to create a login system?
- How do I use a SELECT statement in Python to query a MySQL database?
- How can I use Python to make a MySQL request?
- How can I get the number of rows returned when querying a MySQL database with Python?
See more codes...