简体   繁体   English

python sqlite3进行循环更新

[英]python sqlite3 for loop update

import sqlite3    
conn = sqlite3.connect('sample.db')    
cursor = conn.cursor()    
data = cursor.execute('''SELECT * From Table''')

for i in data:    
    title = i[0]        
    status = i[1]    
    cursor.execute('''UPDATED Table SET status=? WHERE title=?''', (status, title))

cursor.close()    
conn.commit()

I am trying to update over multiple iterations. 我正在尝试更新多个迭代。 However, the script breaks out of the loop as soon as the database makes the first update. 但是,一旦数据库进行第一次更新,该脚本就会脱离循环。 How to fix this? 如何解决这个问题? Thanks! 谢谢!

Use data = data.fetchall() before your loop. 在循环之前使用data = data.fetchall() Otherwise you wind up recycling the cursor inside of your loop (resetting its result set) while you're trying to loop over that result set. 否则,当您试图循环遍历该结果集时,您最终会在循环内回收游标(重置其结果集)。

Using .fetchall() returns a list of results so that you have them stored locally before you re-use the cursor. 使用.fetchall()返回结果列表,以便在重新使用游标之前将它们存储在本地。

Alternatively, create a separate cursor to use for your update statements if you don't want to cache the results of the first query locally. 另外,如果您不想在本地缓存第一个查询的结果,请创建一个单独的游标用于更新语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM