How to Get Id of Row You Just Inserted in Python MySQL


In this example we will show how to get the id of the row you just inserted in Python MySQL.

Source Code

import mysql.connector

# connect to server
mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword",
    db="mydatabase"
)

# get a cursor
mycursor = mydb.cursor()

sql = "INSERT INTO US_STATE (State_name, Abbreviation, Capital, Total_area) VALUES (%s, %s, %s, %s)"
add_val = ('Delaware', 'DE', 'Dover', 2489)

# execute a query
mycursor.execute(sql, add_val)

# put the change into effect
mydb.commit()

print("1 record inserted, ID:", mycursor.lastrowid)

# close the connection
mydb.close()

Output:

1 record inserted, ID: 7
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments