Python

Inserting Multiple Rows Python

Pinterest LinkedIn Tumblr

Inserting Multiple Rows

You can check how to insert multiple rows into the table.

To insert multiple rows into the table, we use the executemany() method. It takes a list of tuples containing the data as a second parameter and a query as the first argument.

import mysql.connector as mysql

db = mysql.connect(
    host="localhost",
    user="root",
    passwd="root@123",
    database="realprogrammer"
)

cursor = db.cursor()

## defining the Query
query = "INSERT INTO user (name, user_name) VALUES (%s, %s)"
## storing values in a variable
values = [
    ("Siddharth", "siddharth18"),
    ("Ashu", "ashu18"),
    ("sumit", "sumit18"),
    ("anand", "anand18")
]

## executing the query with values
cursor.executemany(query, values)

db.commit()

print(cursor.rowcount, "Data Saved")

Write A Comment