Home > Database > Mysql Tutorial > body text

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

PHPz
Release: 2023-05-28 22:01:04
forward
1923 people have browsed it

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()
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template