SQLite3 and lastrowid

Dan M dan at catfolks.net
Tue Nov 16 22:12:14 CET 2010


On Tue, 16 Nov 2010 13:08:15 -0800, fuglyducky wrote:

> On Nov 16, 12:54 pm, Ian <ian.g.ke... at gmail.com> wrote:
>> On Nov 16, 1:00 pm, fuglyducky <fuglydu... at gmail.com> wrote:
>>
>> > Before I added the second table I could simply run
>> > 'print(cursor.lastrowid)' and it would give me the id number.
>> > However, with two tables I am unable to do this.
>>
>> It would help if you would show the code where you're trying to do
>> this.  Without your actual code to look at, we can't tell you why it
>> doesn't work.
>>
>> > Does anyone know if there is a way to reference one table or another
>> > to get lastrowid?
>>
>> cursor.lastrowid is always in reference to the last query executed by
>> the cursor, not in reference to a table.  If you don't capture the
>> value, and then you execute another query on the same cursor, the
>> previous value of cursor.lastrowid no longer exists.  If you need it
>> now, then either you should have captured it when you had the chance,
>> or you should not have executed another query on the same cursor.
>>
>> But perhaps this is not what you're actually trying to do.  I can't
>> tell, because I haven't seen the code.
>>
>> Cheers,
>> Ian
> 
> Thanks for the input. Sorry...I should have included the code...it's
> just a simple query...
> 
> #####################################################
> 
> import sqlite3
> import random
> 
> db_connect = sqlite3.connect('test.db') cursor = db_connect.cursor()
> 
> print(cursor.lastrowid)
> 
> # Choose random index from DB - need to understand lastrowid #row_count
> = cursor.lastrowid
> #random_row = random.randrange(0, row_count)
> 
> cursor.execute("SELECT * FROM table1 WHERE id = 2002")
> print(cursor.fetchmany())

Perhaps insert here:
cursor.execute("SELECT count() from table2")
table2lastRow = cursor.lastrowid()

> 
> #for row in cursor:
>  #   print(row)
> 
> 
> db_connect.commit()
> cursor.close()
> 
> #####################################################




More information about the Python-list mailing list