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.connectorlibrary:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
- Execute an
INSERTquery 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
lastrowidattribute 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 and MySQL to create a login system?
- How can I use Python and MySQL to generate a PDF?
- How can I use Python to retrieve data from MySQL?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to update multiple columns in a MySQL database?
- How can I convert a MySQL query to JSON using Python?
- How do I use Python to connect to a MySQL database using XAMPP?
See more codes...