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?
`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