sqlite&python只提取第一个resu

2024-04-19 12:03:55 发布

您现在位置:Python中文网/ 问答频道 /正文

这很奇怪(令人钦佩的是,这是我第一次尝试使用python/sqlite),但是如果我执行fetchAll()的话,我似乎可以得到所有的行,但除此之外,无论我尝试什么,结果总是只返回第一行,第二次迭代会停止,因为返回的是null。想知道我用python编写代码是否有问题?db似乎没问题。。在

con = sqlite3.connect('backup.db')
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute('select * from tb1;')

for row in cur:
    try:
#       row = dataCur.fetchone()
        #if row == None: break
        print type(row)

        print ' Starting on: %i' % row[0]

        cleaner = Cleaner(scripts=True, remove_tags=['img'], embedded=True)
        try:
            cleaned = cleaner.clean_html(row[2]) #data stored in second col
            cur.execute('update tb1 set data = ? where id = ?;', (cleaned, row[0]))
        except AttributeError:
            print 'Attribute error'

        print ' Ended on: %i' % row[0]

    except IOError:
        print 'IOexception'

Tags: intrueexecutedbdataonconsqlite3
3条回答

每次获取数据之前,必须执行命令/SQL查询。fetchall()fetchone()等。只获取已经执行的内容;因此,当执行一次时,除非已经执行了一个查询,否则不能多次获取。在

您正在重用同一个游标来执行两个不同的查询。尝试使用两个不同的光标,看看这是否解决了您的问题。在

如果我没搞错,那么第二次对游标调用execute时,上一次调用的结果将被丢弃。在

这就是为什么可以使用fetchall,因为它会在您再次调用execute之前返回所有结果。在

对于更新,请使用第二个游标,以避免第一个游标的结果无效。在

相关问题 更多 >