To insert multiple rows into a
MySQL table using Python, you can use the `
executemany()
` method of the cursor object. Here's an example Python program that inserts multiple rows into a `
customers
` table :
Example :
import mysql.connector
# Create a connection to the MySQL server
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# Create a cursor object to execute SQL statements
mycursor = mydb.cursor()
# Define the data to be inserted
data = [
("John", "Highway 21"),
("Peter", "Lowstreet 4"),
("Amy", "Apple st 652"),
("Hannah", "Mountain 21"),
("Michael", "Valley 345")
]
# Insert multiple rows into the table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
mycursor.executemany(sql, data)
# Commit the transaction
mydb.commit()
# Print a message to indicate success
print(mycursor.rowcount, "records inserted.")
# Close the connection
mydb.close()​