Home > Database > Mysql Tutorial > How to Retrieve Auto-Generated Keys After INSERT in MySQL with Python?

How to Retrieve Auto-Generated Keys After INSERT in MySQL with Python?

Susan Sarandon
Release: 2024-12-16 18:29:12
Original
617 people have browsed it

How to Retrieve Auto-Generated Keys After INSERT in MySQL with Python?

Retrieving the Auto-Generated Key after an INSERT Statement in MySQL with Python

When performing an INSERT operation in a MySQL database using Python, it is often necessary to retrieve the primary key or auto-generated ID of the newly inserted row. This can be useful for referencing the inserted row in subsequent operations or for maintaining the uniqueness of the row.

Using cursor.lastrowid

The Python MySQL Connector provides a cursor object that, when initialized, can be used to execute SQL statements and retrieve resulting data. After an INSERT statement has been executed, the cursor.lastrowid attribute contains the primary key or auto-generated ID of the newly inserted row.

For example, consider the following code:

import mysql.connector

conn = mysql.connector.connect(...)
cursor = conn.cursor()
cursor.execute("INSERT INTO mytable(height) VALUES(%s)", (height))
inserted_id = cursor.lastrowid
Copy after login

In this code, the lastrowid attribute is retrieved and stored in the inserted_id variable. This ID represents the primary key of the newly inserted row.

Using connection.insert_id()

Alternatively, the connection object itself provides an insert_id attribute that returns the ID of the last row inserted through the connection. This attribute is available even after the cursor has been closed.

The following code demonstrates how to use connection.insert_id():

import mysql.connector

conn = mysql.connector.connect(...)
cursor = conn.cursor()
cursor.execute("INSERT INTO mytable(height) VALUES(%s)", (height))
inserted_id = conn.insert_id()
Copy after login

Regardless of the method used, the retrieved insert_id or lastrowid can be utilized to identify the newly inserted row in the database.

The above is the detailed content of How to Retrieve Auto-Generated Keys After INSERT in MySQL with 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