为什么“ c.execute(...)”会中断循环?

Ada*_*dam 3 python sqlite

我正在尝试更改sqlite3文件中的一些数据,而我在python和google-fu中不存在的知识使我最终获得了以下代码:

#!/usr/bin/python
# Filename : hello.py

from sqlite3 import *

conn = connect('database')

c = conn.cursor()

c.execute('select * from table limit 2')

for row in c:
    newname = row[1]
    newname = newname[:-3]+"hello"
    newdata = "UPDATE table SET name = '" + newname + "', originalPath = '' WHERE id = '" + str(row[0]) + "'"
    print row
    c.execute(newdata)
    conn.commit()
c.close()
Run Code Online (Sandbox Code Playgroud)

它在第一行上像超级按钮一样工作,但是由于某种原因,它只运行一次循环(仅修改表中的第一行)。当我删除“ c.execute(newdata)”时,它将按需循环遍历表中的前两行。我该如何运作?

Mat*_*ips 5

之所以这样做,是因为一旦您完成操作c.execute(newdata),光标就不再指向原始结果集了。我会这样:

#!/usr/bin/python
# Filename : hello.py

from sqlite3 import *

conn = connect('database')

c = conn.cursor()

c.execute('select * from table limit 2')
result = c.fetchall()

for row in result:
    newname = row[1]
    newname = newname[:-3]+"hello"
    newdata = "UPDATE table SET name = '" + newname + "', originalPath = '' WHERE id = '" + str(row[0]) + "'"
    print row
    c.execute(newdata)
conn.commit()    
c.close()
conn.close()
Run Code Online (Sandbox Code Playgroud)