Home >Database >Mysql Tutorial >How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL using Python?

How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL using Python?

DDD
DDDOriginal
2024-12-02 14:30:13464browse

How to Retrieve the Auto-Generated Primary Key After an INSERT in MySQL using Python?

Retrieving the Primary Key after Inserting into a MySQL Database with 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn