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
Release: 2024-12-03 20:37:10
Original
763 people have browsed it

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))
Copy after login

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

last_inserted_id = cursor.lastrowid
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template