python-mysqlHow can I get the ID of a newly inserted row in a MySQL database using Python?
To get the ID of a newly inserted row in a MySQL database using Python, the following steps should be taken:
- Connect to the MySQL database using the
mysql.connector
library:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
- Execute an
INSERT
query to add a row to the database:
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
- Use the
lastrowid
attribute of the cursor object to get the ID of the newly inserted row:
print(mycursor.lastrowid)
Output example
1
- Finally, commit the changes to the database using the
commit()
method:
mydb.commit()
For more information, see the MySQL Connector Python documentation.
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How do I access MySQL using Python?
- How can I retrieve unread results from a MySQL database using Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How do I decide between using Python MySQL and PyMySQL?
- How do I use an online compiler to write Python code for a MySQL database?
- How can I resolve the "no database selected" error when using Python and MySQL?
- How can I get the number of rows returned when querying a MySQL database with Python?
See more codes...