2010-12-17 71 views
2

我试图改变一个sqlite3的文件中的一些数据,我我不存在的知识,Python和谷歌福让我结束了这段代码:为什么“c.execute(...)”会打破循环?

#!/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)”时,它循环遍历表中的前两行,因为它应该。我如何使它工作?

回答

3

这样做是因为一旦你做了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() 
1

当您致电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() 
+0

虽然你不需要2个游标吗?只需保存第一个执行调用的结果并迭代即可。 – 2010-12-17 15:38:30

+0

@Matt:我没有注意到那里的'LIMIT 2'。你是对的。 – sje397 2010-12-18 01:08:22

0

因为重复使用“C”环路内的无效“C”您正在使用的循环迭代。为循环中的查询创建一个单独的游标。

0

您正在使用相同的游标执行更新,Update不返回任何行,因此对于c中的行评估为false。