Home >Database >Mysql Tutorial >How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL using Python?
When inserting data into a MySQL database using Python, you might want to retrieve the primary key generated for the newly created row. Here's how you can accomplish this:
Using cursor.lastrowid
The cursor.lastrowid attribute contains the ID of the last row inserted using that cursor object. You can use this attribute after calling execute() with your INSERT statement:
cursor.execute("INSERT INTO mytable(height) VALUES(%s)", (height)) last_inserted_id = cursor.lastrowid
Using connection.insert_id()
Alternatively, you can use the connection.insert_id() method to get the last inserted ID on a specific connection. This method is available on the connection object that you used to execute the insert query:
connection.execute("INSERT INTO mytable(height) VALUES(%s)", (height)) last_inserted_id = connection.insert_id()
Note: These methods retrieve the ID of the last row inserted on the specific cursor or connection object, not necessarily the ID of the row you just inserted. If multiple INSERT statements are executed on the same object, the returned ID might not correspond to the last row you inserted.
The above is the detailed content of How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL using Python?. For more information, please follow other related articles on the PHP Chinese website!