Retrieving Last Inserted ID after INSERT into MySQL Database with Python
When performing INSERT operations into a MySQL database using Python, obtaining the primary key of the newly inserted row can be crucial for further processing or referencing the data. This article provides a detailed explanation and code examples on how to retrieve the last inserted ID in Python.
Using cursor.lastrowid
The cursor.lastrowid attribute provides the ID of the last inserted row for the current cursor. To use this approach, you need to:
import mysql.connector # Establish the MySQL connection connection = mysql.connector.connect(...) # Create a cursor object cursor = connection.cursor() # Execute the INSERT statement cursor.execute("INSERT INTO mytable(height) VALUES(%s)", (height)) # Get the last inserted ID last_inserted_id = cursor.lastrowid
Using connection.insert_id()
Another method to retrieve the last inserted ID is through the connection.insert_id() method, which returns the last ID generated for the specified connection. This approach is useful when you need to retrieve the ID from outside the context of the cursor that executed the INSERT statement.
# Execute the INSERT statement connection.cursor().execute("INSERT INTO mytable(height) VALUES(%s)", (height)) # Get the last inserted ID from the connection last_inserted_id = connection.insert_id()
By following these methods, you can easily retrieve the last inserted "id" value after executing an INSERT operation into a MySQL database using Python.
The above is the detailed content of How to Retrieve the Last Inserted ID in MySQL using Python?. For more information, please follow other related articles on the PHP Chinese website!