简体   繁体   中英

How to fetch the primary key value of a recently inserted row

import MySQLdb

How to fetch the primary key value of a recently inserted row, in the following execution.

cursor = mysql.cursor()
cursor.execute("""INSERT INTO foos (val1,val2) VALUES (%s,%s)""", (v1, v2))

From the docs :

Cursor.lastrowid

This read-only attribute provides the rowid of the last modified row (most databases return a rowid only when a single INSERT operation is performed).

您可以在表上添加时间戳,并使用now() - interval 1 hour例如now() - interval 1 hour来获取

Ignacio's answer is more appropriate for the API you're using but in general.

MySQL allows you to get the ID of the most recent insert.

SELECT LAST_INSERT_ID();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM