SQLite3 and lastrowid

fuglyducky fuglyducky at gmail.com
Wed Nov 17 00:48:33 CET 2010


On Nov 16, 1:52 pm, Ian <ian.g.ke... at gmail.com> wrote:
> On Nov 16, 2:08 pm, fuglyducky <fuglydu... at gmail.com> wrote:
>
> > db_connect = sqlite3.connect('test.db')
> > cursor = db_connect.cursor()
>
> > print(cursor.lastrowid)
>
> At this point you haven't executed a query yet, so there is no
> meaningful value that cursor.lastrowid can take.
>
> > # Choose random index from DB - need to understand lastrowid
> > #row_count = cursor.lastrowid
> > #random_row = random.randrange(0, row_count)
>
> This is wrong.  The lastrowid is not the number of rows in the table.
> It's the row-id of the row that was inserted (if any) by the last
> query executed by the cursor.  In the case of sqlite3, I think the row-
> id is just the primary key if it's an integer (but in general the row-
> id is database-dependent), so you *might* be able to get away with it
> if you always let it autoincrement when inserting, never delete any
> rows, and never change their primary keys.  But it's unreliable and
> only available immediately after an insert, so don't do it that way.
>
> The proper way to get the number of rows is to use the COUNT aggregate
> function, e.g., "SELECT COUNT(*) FROM TABLE1", which will return a
> single row with a single column containing the number of rows in
> table1.
>
> Cheers,
> Ian

Ahhh...great...thanks for the info! I'll do the row count then!!!



More information about the Python-list mailing list