Henrik Holen
Henrik Holen

Reputation: 23

How can I check if SQLite cursor result from a SELECT statement is empty?

I've tried using fetchone() and it works, but the problem is that it removes the first entry from the list in the cases where I do have items in the result.

results = cursor.execute('SELECT ID, text FROM mytable')
if results.fetchone() is None:
    print "**********"
    print "No entries"
    print "**********"
else:
    for row in results:
        print "\t%s: %s" % (row[0], row[1])

Is there a way to find out if "results" is empty without fetching from it?

Upvotes: 2

Views: 8174

Answers (5)

LexyStardust
LexyStardust

Reputation: 1018

This isn't the most elegant, but it should work right?

results = cursor.execute('SELECT ID, text FROM mytable')
done_stuff = False
for row in results:
    done_stuff = True
    # do the stuff you want to do
if not done_stuff:
    print("didn't do stuff")

It doesn't matter if you do the check at the end as the for-loop is going to end instantly with an empty result set.

Upvotes: 0

Anup
Anup

Reputation: 200

Use the cursor to fetching records not a result variable because cursor not return any values, so replace this :

     $ results = cursor.execute('SELECT ID, text FROM mytable')
     $ if cursor.fetchone() is None:
     $    print "**********"
     $     print "No entries"
     $     print "**********"
     $ else:
     $     for row in cursor:
               print "\t%s: %s" % (row[0], row[1])

Now it will work...

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142176

SQLite is somewhat awkward like that as you have to .fetchone() to see if you get a result. There is a read-ahead work-around though (which can be used on iterables in general).

from itertools import chain
try:
    first_row = next(results)
    for row in chain((first_row,), results):
        pass # do something
except StopIteration as e:
    pass # 0 results

Upvotes: 4

Paulo Freitas
Paulo Freitas

Reputation: 13649

res = cursor.execute('SELECT ID, text FROM mytable')

try:
    first_row = res.next()

    for row in [first_row] + res.fetchall():
        print '\t%s: %s' % (row[0], row[1])
except StopIteration as e:
    print 'No entries'

Upvotes: 0

user647772
user647772

Reputation:

No. rowcount exists but is always -1.

Upvotes: 0

Related Questions