Updating SQLite table with Python function using table columns as arguments -


i trying update records of table results of function uses other rows of table arguments. however, result of operation records repeated first record. can explain why might case?

def fun(a,b,c,d):     return + b + c + d  cur = conn.cursor()  cur.execute("select field1, field2, field3, field4 table1")  row in cur:         cur.execute("update table1 set field5 = ?", (fun(row[0],row[1],row[2],row[3]),)) 

the completed table looks this:

field1, field2, field3, field4, field5 4, 3, 2, 1, 10 7, 3, 1, 0, 10 8, 5, 2, 0, 10 

when should this:

field1, field2, field3, field4, field5 4, 3, 2, 1, 10 7, 3, 1, 0, 11 8, 5, 2, 0, 15 

first, select of rows:

select field1, field2, field3, field4 table1 

this yields result set in cur:

4, 3, 2, 1 7, 3, 1, 0 8, 5, 2, 0 

you begin iterate through rows. start first row:

4, 3, 2, 1 

you add columns together, correctly yielding result 10. execute sql statement:

update table1 set field5 = 10 

whoa, there! there's no where clause! you've changed field5 of every single row! that's problem #1: you need add where clause. tables have primary key, if have primary key, you'll want add clause where id = ?. if don't have primary key, best can include other columns, e.g.

update table1 set field5 = ? field1 = ? , field2 = ? , field3 = ? , field4 = ? 

make sure provide value each ? in execute call.


so you've finished executing update statement on cur cursor. go iterate again… and there's no more rows. why? because update statement changed result set of cursor, discarding remaining rows of select. you need run updates on different cursor or fetch rows before move on updating.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -