Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sqlite

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?

like image 939
Adam Avatar asked Dec 28 '22 03:12

Adam


2 Answers

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()
like image 111
Matt Phillips Avatar answered Dec 30 '22 16:12

Matt Phillips


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()
like image 40
sje397 Avatar answered Dec 30 '22 17:12

sje397