Home > Database > Mysql Tutorial > How to Retrieve the Last Inserted ID in MySQL using Python?

How to Retrieve the Last Inserted ID in MySQL using Python?

Linda Hamilton
Release: 2024-12-02 11:21:10
Original
529 people have browsed it

How to Retrieve the Last Inserted ID in MySQL using Python?

Retrieving Last Inserted ID after INSERT into MySQL Database with Python

When performing INSERT operations into a MySQL database using Python, obtaining the primary key of the newly inserted row can be crucial for further processing or referencing the data. This article provides a detailed explanation and code examples on how to retrieve the last inserted ID in Python.

Using cursor.lastrowid

The cursor.lastrowid attribute provides the ID of the last inserted row for the current cursor. To use this approach, you need to:

import mysql.connector

# Establish the MySQL connection
connection = mysql.connector.connect(...)

# Create a cursor object
cursor = connection.cursor()

# Execute the INSERT statement
cursor.execute("INSERT INTO mytable(height) VALUES(%s)", (height))

# Get the last inserted ID
last_inserted_id = cursor.lastrowid
Copy after login

Using connection.insert_id()

Another method to retrieve the last inserted ID is through the connection.insert_id() method, which returns the last ID generated for the specified connection. This approach is useful when you need to retrieve the ID from outside the context of the cursor that executed the INSERT statement.

# Execute the INSERT statement
connection.cursor().execute("INSERT INTO mytable(height) VALUES(%s)", (height))

# Get the last inserted ID from the connection
last_inserted_id = connection.insert_id()
Copy after login

By following these methods, you can easily retrieve the last inserted "id" value after executing an INSERT operation into a MySQL database using Python.

The above is the detailed content of How to Retrieve the Last Inserted ID 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