python-mysqlHow do I get the ID of the inserted row in a MySQL database using Python?
The ID of the inserted row in a MySQL database can be obtained using Python with the help of the mysql.connector
library. Here is an example code block demonstrating how to do this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print("1 record inserted, ID:", mycursor.lastrowid)
The output of the code above would be:
1 record inserted, ID: 8
The code consists of the following parts:
- Importing the
mysql.connector
library. - Establishing a connection to the MySQL database.
- Creating a cursor object.
- Writing an SQL query to insert a row into the database.
- Executing the query with the values to be inserted.
- Committing the changes to the database.
- Printing the ID of the inserted row.
Helpful links
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 to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I connect Python to a MySQL database using an Xserver?
- How can I troubleshoot a Python MySQL OperationalError?
- How do I check the version of MySQL I am using with Python?
- How do I use Python to handle MySQL NULL values?
See more codes...