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

これは最もエレガントではありませんが、正しく機能するはずですか?

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 に答える
0

No. rowcount exists but is always -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 に答える