2012-07-24 90 views
2

我试过使用fetchone(),它的工作原理,但问题是,它在结果中有项目的情况下从列表中删除第一个条目。如何检查SELECT语句的SQLite游标结果是否为空?

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

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

+0

只要在results.fetchall()中做'行':'。为什么要检查一个空的结果? – 2012-07-24 11:54:02

回答

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 
+0

谢谢,这就像一个魅力工作(并教我一些新的) – 2012-07-24 18:13:21

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

现在将工作...

+0

这似乎并不奏效。我猜是因为Python通过引用处理调用的方式。 – 2012-07-24 18:04:59

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循环没关系,是要与查询结果为空立即结束。