sqlite3 question

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 12 10:30:24 CEST 2007


En Thu, 12 Apr 2007 04:38:06 -0300, Jorgen Bodde  
<jorgen.maillist at gmail.com> escribió:

> I am using sqlite3 in python, and I wonder if there is a way to know
> if there are valid rows returned or not. For example I have a table
> song with one entry in it. The ID of that entry is 1, so when I do;
>
>>>> r = c.execute('select * from song where id = 1')
>>>> for s in r:
> ... 	print s
> ... 	
> (1, u'Spikedrivers Blues', u'Mississippi John Hurt')
>
> That works. But when I can't restore the row by e.g. an ID that does
> not exist, I cannot see any method in 'r' (which is a SQLite.Cursor)
> that can tell me if I have rows. As explained in the help, r.rowcount
> does not give a valid result because it can't determine how many rows
> are restored in advance.

If you are only interested on how many songs there are, use count(*):
c.execute('select count(*) from song where id = 1')
print c.fetchone()[0]

If you are going to process the results, just iterate over the rows as in  
your example.
Or, use the fetchone method; it returns the first row, or None if no data  
is available (don't forget to process that row too).
If you don't expect many rows, you can use rows = list(c), or rows =  
c.fetchall(), and check len(rows).

> I am pretty new with Python, maybe there are some properties of an
> iterator / sqlite3 I am not aware of that can tell me how many rows
> are there?

As with many "generic" iterators, unfortunately, you have to consume the  
elements in order to know its length.

-- 
Gabriel Genellina




More information about the Python-list mailing list