Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of lastrowid after "insert or ignore"

I am using sqlite, and I have a Python code as follows:

...
cur.execute("insert or ignore into books (title, authors, ...) \
values (:title, :authors, ..."), locals())
...
bookId = cur.lastrowid

If the ignore part of the select statement applies

then the value of cur.lastrowid is 0.

But this is not what I want. I'd like to get books.id value from the database in any case.

Should I use select statement or is there smarter way to achieve it?

My temporary solution:

if bookId == 0:
    cur.execute("select id from books where \
    title = :title and authors = :authors", locals())
    bookId = cur.fetchone()[0]  
like image 957
xralf Avatar asked Jun 28 '13 16:06

xralf


2 Answers

There is no better way. To read some existing value from the database, there's only SELECT.

like image 96
CL. Avatar answered Oct 15 '22 22:10

CL.


Try using on duplicate key update id=LAST_INSERT_ID(id) for the PK. Seems like lastrowID will be correct from then on out.

like image 29
Amalgovinus Avatar answered Oct 15 '22 22:10

Amalgovinus