为什么"c.execute(...)"会中断循环?
我正在尝试修改一个sqlite3文件中的一些数据,但由于我对python和搜索的了解非常有限,最后写出了这样的代码:
#!/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()
这个代码在处理第一行数据时效果很好,但不知为何它只执行了一次循环(只有表格中的第一行被修改)。当我去掉“c.execute(newdata)”这行时,它就能正常循环处理前两行数据。请问我该怎么做才能让它正常工作呢?
4 个回答
0
因为在循环里重复使用“c”会让你用作循环计数的“c”失效。你应该为循环中的查询创建一个单独的游标。
3
当你调用 c.execute(newdata)
时,它会改变光标 c
的状态,这样当你写 for row in c:
时,它会立刻结束,不会继续执行。
试试这个:
c = conn.cursor()
c2 = 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
c2.execute(newdata)
conn.commit()
c2.close()
c.close()
7
之所以会这样,是因为当你执行 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()