Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sqlite3 for loop update

Tags:

python

import sqlite3    
conn = sqlite3.connect('sample.db')    
cursor = conn.cursor()    
data = cursor.execute('''SELECT * From Table''')

for i in data:    
    title = i[0]        
    status = i[1]    
    cursor.execute('''UPDATED Table SET status=? WHERE title=?''', (status, title))

cursor.close()    
conn.commit()

I am trying to update over multiple iterations. However, the script breaks out of the loop as soon as the database makes the first update. How to fix this? Thanks!

like image 757
Aaron Phalen Avatar asked Oct 23 '25 18:10

Aaron Phalen


1 Answers

Use data = data.fetchall() before your loop. Otherwise you wind up recycling the cursor inside of your loop (resetting its result set) while you're trying to loop over that result set.

Using .fetchall() returns a list of results so that you have them stored locally before you re-use the cursor.

Alternatively, create a separate cursor to use for your update statements if you don't want to cache the results of the first query locally.

like image 112
Amber Avatar answered Oct 26 '25 06:10

Amber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!