Home >Database >Mysql Tutorial >How to Retrieve Auto-Increment IDs After an INSERT in MySQL using Python?

How to Retrieve Auto-Increment IDs After an INSERT in MySQL using Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 20:37:10758browse

How to Retrieve Auto-Increment IDs After an INSERT in MySQL using Python?

Obtaining Auto-Increment ID After an INSERT with Python and MySQL

When performing an INSERT INTO operation in a MySQL database using Python, it is often necessary to retrieve the primary key of the newly inserted row. In this case, the table has an auto-incrementing id column as the primary key.

To obtain the ID after an insertion, there are two main methods available using Python:

cursor.lastrowid

The cursor.lastrowid attribute contains the ID of the last row inserted using the cursor. After executing the INSERT statement:

cursor.execute("INSERT INTO mytable(height) VALUES(%s)", (height))

The id of the newly inserted row can be accessed as follows:

last_inserted_id = cursor.lastrowid

connection.insert_id()

Alternatively, the connection.insert_id() method can be used to obtain the ID of the last row inserted on the connection. This method is typically used in conjunction with a separate INSERT statement executed outside of a cursor context:

connection.execute("INSERT INTO mytable(height) VALUES(%s)", (height))
last_inserted_id = connection.insert_id()

The above is the detailed content of How to Retrieve Auto-Increment IDs 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