To get the ID of the last inserted row in a MySQL table using Python, you can use the `
lastrowid
` property of the cursor object.
Here's an example Python program that inserts a row into a `
customers
` table and retrieves the ID of the inserted row :
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()
# Insert a row into the table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
# Commit the transaction
mydb.commit()
# Print the ID of the inserted row
print("The ID of the last inserted row is:", mycursor.lastrowid)
# Close the connection
mydb.close()​