views:

813

answers:

2

Hi, I am trying to get the rowcount of a sqlite3 cursor in my Python3k program, but I am puzzled, as the rowcount is always -1, despite what python3 docs say (actually it is contradictory, it should be None). Even after fetching all the rows, rowcount stays at -1. Is it a Sqlite3 implementation bug? A Sqlite3 bug? I have already checked if there are rows in the table.

I can get around this checking if a fetchone() returns something different than None, but I thought this issue would be nice to discuss.

Thanks.

+1  A: 

From the documentation:

As required by the Python DB API Spec, the rowcount attribute “is -1 in case no executeXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface”.

This includes SELECT statements because we cannot determine the number of rows a query produced until all rows were fetched.

That means all SELECT statements won't have a rowcount. The behaviour you're observing is documented.

EDIT: Documentation doesn't say anywhere that rowcount will be updated after you do a fetchall() so it is just wrong to assume that.

nosklo
But after fetching them with cur.fetchall() neither?
Hiperi0n
Documentation doesn't say anywhere that rowcount will be updated after you do a fetchall() so it is just wrong to assume that.
nosklo
+1  A: 

Instead of "checking if a fetchone() returns something different than None", I suggest:

cursor.execute('SELECT * FROM foobar')
for row in cursor:
   ...

this is sqlite-only (not supported in other DB API implementations) but very handy for sqlite-specific Python code (and fully documented, see http://docs.python.org/library/sqlite3.html).

Alex Martelli