Python manipulates how MySQL gets the primary key id for inserting data
This article is about how Python operates MySQL to get id, the primary key of inserting data. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Get the primary key id for inserting data
Import pymysql database= pymysql.connect (host= "127.0.0.1", port=3306, user= "root", password= "root", database= "test") cursor = database.cursor () for i in range (5): cursor.execute ('insert into test (name) values ("test") print (database.insert_id () database.commit () cursor.close () database.close ()
You can get the primary key id of the inserted data through the db.insert_id () method, and be sure to get it before commit, otherwise 0 is returned.
Thank you for reading! This is the end of this article on "Python operation MySQL how to get the primary key id of inserting data". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!