How do I get the "id" after INSERT into MySQL database with Python?

TIMEX picture TIMEX · Mar 30, 2010 · Viewed 149.8k times · Source

I execute an INSERT INTO statement

cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))

and I want to get the primary key.

My table has 2 columns:

id      primary, auto increment
height  this is the other column.

How do I get the "id", after I just inserted this?

Answer

Amber picture Amber · Mar 30, 2010

Use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.