0

I am building an application on Google App Engine in Python that uses mysql. When I insert a new row in a table with autoincrement, I need to retrieve the autogenerated ID. Several posts, including the following two, have suggested using "SELECT LAST_INSERT_ID();", but that does not work.

PHP/MySQL insert row then get 'id'

Query-getting last inserted row id in mysql using query

What I get when using that command is instead the first of all IDs. My code looks like this:

cursor.execute("INSERT INTO tablename (val1, val2) VALUES ("foobar", 42);")
last_id = cursor.execute("SELECT LAST_INSERT_ID();")

Is there some other way of doing this?

Community
  • 1
  • 1
NiklasR
  • 473
  • 6
  • 19

1 Answers1

0

The SQL is correct but the Python is not. cursor.execute() returns the number of rows affected, not the result of the operation. You need to call cursor.fetchone() to get the actual result, which will be a tuple.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks, this did solve it. For the purpose of clarity, here is the final code (apologies for the missing line breaks):
    `cursor.execute("INSERT INTO tablename (val1, val2) VALUES ('foobar', 42);")
    cursor.execute("SELECT LAST_INSERT_ID() FROM tablename")
    last_id = cursor.fetchone()[0]`
    – NiklasR May 02 '15 at 06:57