Python MySQL – Insert Data

We add data to a MySQL table with the SQL INSERT INTO command. This chapter uses the users table created in the previous chapter.


Insert one row

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="student"
)
cursor = conn.cursor()

sql = "INSERT INTO users (name, mobile, email) VALUES (%s, %s, %s)"
values = ("Robin", "9876543210", "robin@example.com")

cursor.execute(sql, values)
conn.commit()

print(cursor.rowcount, "record inserted")
print("Last id:", cursor.lastrowid)

cursor.close()
conn.close()
Output of the above program is

1 record inserted
Last id: 1

  • %s is a placeholder. MySQL puts the real values in its place safely.
  • conn.commit() is required. Without it the data is not saved in the table.
  • cursor.rowcount tells how many rows were added.
  • cursor.lastrowid is the auto increment id of the new row. It is 1 here, because the table was empty.
Note: Never build the SQL with string joining or f-strings, like "... VALUES ('" + name + "')". A user can then break your query (SQL injection). Always pass the values separately, as shown above.

Insert many rows

Use executemany() with a list of tuples to add many rows with one command.

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="student"
)
cursor = conn.cursor()

sql = "INSERT INTO users (name, mobile, email) VALUES (%s, %s, %s)"
values = [
    ("Maria", "9123456780", "maria@example.com"),
    ("John", "9012345678", "john@example.com")
]

cursor.executemany(sql, values)
conn.commit()

print(cursor.rowcount, "records inserted")

cursor.close()
conn.close()
Output of the above program is

2 records inserted


Summary

  • Use INSERT INTO with %s placeholders and pass the values as a tuple.
  • Call conn.commit() to save the changes.
  • Use executemany() for many rows.
  • Next: select data from the table.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Python program to add two numbers
Python program to swap two variables
Python program to find the area of a circle
Python program to convert Celsius to Fahrenheit
Python program to check even or odd number
Python program to find the largest of three numbers
Python program to check leap year
Interview Questions & Answers
What is Python?
Is Python an interpreted language?
What is an interpreted language?
What is PEP 8?
What is a list in Python?
What is a tuple in Python?
What is a set in Python?