开发者

Why does "c.execute(...)" break the loop?

开发者 https://www.devze.com 2023-01-30 20:16 出处:网络
I am trying to change some data in an sqlite3 file and I my non-existing knowledge in python and google-fu made me end up with this code:

I am trying to change some data in an sqlite3 file and I my non-existing knowledge in python and google-fu made me end up with this code:

#!/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()

It works like a charm on the first row but for some reason it only runs the loop one time (only the first row in the table gets modified). When I remove "c.execute(newdata)" it loops through the first two rows in the table, as it should. How do I make it work?


It's doing that because as soon as you do c.execute(newdata) the cursor is no longer pointing at the original result set anymore. I would do it this way:

#!/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()


When you call c.execute(newdata), it changes the cursor c so that for row in c: exits immediately.

Try:

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()


Because reusing "c" inside the loop invalidates the "c" you're using as the loop iterator. Make a separate cursor for the queries in the loop.


You are using the same cursor to do the update, Update does not return any rows so for row in c evaluate to false.

0

精彩评论

暂无评论...
验证码 换一张
取 消