Python MySql - Insert Records into Table



Python uses c.execute(q) function to insert a record(s) in a table where c is cursor and q is the insert query to be executed.

Syntax

# execute SQL query using execute() method.
cursor.execute(sql)

# commit the record
db.commit()

# get the row id for inserted record
print("ID:", cursor.lastrowid)

# print the number of records inserted
print(mycursor.rowcount, "records inserted.")
Sr.No. Parameter & Description
1

$sql

Required - SQL query to insert record(s) in a table.

Example - Inserting records in a table

Try the following example to insert records in a table −

Copy and paste the following example as main.ty −

main.py

import mysql.connector

# Open database connection
db = mysql.connector.connect(host="localhost",user="root",password="root@123", database="TUTORIALS")

# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = """INSERT INTO tutorials_tbl
         (tutorial_title,tutorial_author, submission_date) 
         VALUES ('HTML 5', 'Robert', '2010-02-10'),
         ('Java', 'Julie', '2020-12-10'),
         ('JQuery', 'Julie', '2020-05-10')
         """

# execute SQL query using execute() method.
cursor.execute(sql)

# commit the record
db.commit()

# get the row id for inserted record
print("ID:", cursor.lastrowid)

# print the number of records inserted
print(cursor.rowcount, "records inserted.")

# disconnect from server
db.close()

Output

Execute the main.py script using python and verify the output.

ID: 5
3 records inserted.
Advertisements