MySQLdb: getting inserted data

Gerhard Häring gh at ghaering.de
Tue Apr 15 23:42:00 CEST 2003


* Mirko Koenig <koenig at v-i-t.de> [2003-04-15 22:31 +0200]:
> Hi
> 
> I want to insert a new empty row into my table and get the value of the
> primary key, so that i can identify it. [...]

Use the .lastrowid property of the cursor object. It's an optional
DB-API extension that MySQLdb implements. E. g.:

# cx is the connection object
cu = cx.cursor()
name = "Alice"
cu.execute("INSERT INTO PERSON(PERS_NAME) VALUES (%s)", (name,))

title = "Macbeth"
# BK_OWNER is the foreign key that refers to the PERSON table:
cu.execute("INSERT INTO BOOKS(BK_TITLE, BK_OWNER) VALUES (%s, %i)",
        (title, cu.lastrowid))
cx.commit()     # These two INSERTs are atomic

HTH,

Gerhard
-- 
mail:   gh at ghaering.de
web:    http://ghaering.de/





More information about the Python-list mailing list