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:
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
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!