Google News
logo
Python Program to Get inserted ID
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()​
In the above example, the program inserts a single row into the `customers` table using the `execute()` method of the cursor object. The statement is the same as in the previous examples.

After the row has been inserted, the program retrieves the ID of the inserted row using the `lastrowid` property of the cursor object. This property returns the ID of the last inserted row in the current session, which in this case is the row that was just inserted.

Finally, the program prints the ID of the inserted row and closes the connection.