Sam
Sam

Reputation: 8703

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))

Upvotes: 1

Views: 79

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799370

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).

Upvotes: 2

Danack
Danack

Reputation: 25721

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();

Upvotes: 1

WeaselFox
WeaselFox

Reputation: 7400

You can add a a timestamp on your table and fetch using now() - interval 1 hour for example

Upvotes: 1

Related Questions