如何检查SELECT语句的SQLite游标结果是否为空?

时间:2012-07-24 11:47:20

标签: python sqlite

我尝试过使用fetchone()并且它可以正常工作,但问题是如果我在结果中有项目,它会从列表中删除第一个条目。

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])

有没有办法找出“结果”是否为空而没有从中获取?

5 个答案:

答案 0 :(得分:4)

SQLite有点尴尬,因为你必须.fetchone()看看你是否得到了结果。虽然有一个预读的解决方法(一般可用于迭代)。

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

答案 1 :(得分:0)

没有。 rowcount已存在,但始终为-1

答案 2 :(得分:0)

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'

答案 3 :(得分:0)

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])

现在它会起作用......

答案 4 :(得分:0)

这不是最优雅的,但它应该可以正常工作吗?

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")

如果您在结尾处进行检查并不重要,因为for循环将立即以空结果集结束。