2010-12-17 63 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。