2

我已经尝试使用 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])

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

4

5 回答 5

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
于 2012-07-24T12:26:59.677 回答
0

rowcount存在,但始终是-1

于 2012-07-24T11:57:39.243 回答
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'
于 2012-07-24T12:43:32.413 回答
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])

现在它将起作用...

于 2012-07-24T13:41:39.777 回答
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 循环将立即以空结果集结束。

于 2012-07-24T14:06:50.603 回答