简体   繁体   中英

Update table using a list of dictionaries

I have a list of dicts, this is actually a result from a previous select that I've converted to a dict (this was so I could edit the values of some columns):

sql_select = "SELECT key1, key2, value1, value2 FROM table_a"
self.dbcur.execute(sql_select)
matchedrows = self.dbcur.fetchall()

dictrows = [dict(row) for row in matchedrows]
for row in dictrows:
    ....process data, update some fields etc.

Now I would like to write my changes back to my sqlite table, my obvious choice was to try an update statement but I'm failing miserably trying to construct it (lack of knowledge)

sql_update = ('UPDATE table_a SET value1 = ?, value2 = ? WHERE key1 = ? and key2 =?')
self.dbcur.execute(sql_update, dictrows)
self.dbcon.commit()

Is this possible to do? Or should I be looking at an alternative method such as inserting to a temp table, etc.?

The sqlite3 database adapter takes named parameters in the form :keyname . Combined with cursor.executemany() you can use this to turn your list of dictionaries into a series of UPDATE statements:

sql_update = ('''\
    UPDATE table_a SET value1 = :value1, value2 = :value2
    WHERE key1 = :key1 and key2 = :key2''')
self.dbcur.executemany(sql_update, dictrows)

For each dictionary in the dictrows list, the query takes the keys value1 , value2 , key1 and key2 from the dictionary as SQL parameters and executes the UPDATE statement.

You'd have to use actual key names from your dictionaries, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM