Home  >  Article  >  Database  >  How to get the primary key id of inserted data in Python using MySQL

How to get the primary key id of inserted data in Python using MySQL

PHPz
PHPzforward
2023-05-28 22:01:041868browse

Get the primary key id of the inserted 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()

The primary key id of the inserted data can be obtained through the db.insert_id() method. Note that it must be obtained before commit, otherwise 0 will be returned.

The above is the detailed content of How to get the primary key id of inserted data in Python using MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete