python-mysqlHow can I retrieve the last insert ID in MySQL using Python?
The last insert ID in MySQL can be retrieved using Python by executing a query on the database. This can be done using the MySQL Connector/Python library.
The following example code block shows how to use the lastrowid
method to retrieve the last insert ID:
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
cursor = db.cursor()
# Execute an INSERT query
cursor.execute("INSERT INTO table1 (column1, column2) VALUES (value1, value2)")
# Retrieve the last insert ID
last_insert_id = cursor.lastrowid
print(last_insert_id)
# Output: 12
The lastrowid
method returns an integer which is the last insert ID of the query. This can then be used to reference the row which was just inserted.
More of Python Mysql
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I use Yum to install the MySQLdb Python module?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to show the MySQL processlist?
- How can I use Python to retrieve data from MySQL?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to connect to a MySQL database using XAMPP?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
See more codes...