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 can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python and MySQL?
- How do Python and MySQL compare to MariaDB?
- How do I use Python to update multiple columns in a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How can I connect to MySQL using Python?
- How do I use Python to authenticate MySQL on Windows?
- How can I convert a MySQL database to a SQLite database using Python?
See more codes...