简体   繁体   English

使用字典列表更新表

[英]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): 我有一个dicts列表,这实际上是我之前选择的一个结果,我已经转换为dict(这是我可以编辑某些列的值):

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) 现在我想把我的更改写回我的sqlite表,我明显的选择是尝试更新语句,但我很难勉强尝试构建它(缺乏知识)

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 . sqlite3数据库适配器以以下形式获取命名参数:keyname Combined with cursor.executemany() you can use this to turn your list of dictionaries into a series of UPDATE statements: 结合cursor.executemany()您可以使用cursor.executemany()您的词典列表转换为一系列UPDATE语句:

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. 对于dictrows列表中的每个字典,查询将字典中的键值value1value2key1key2作为SQL参数,并执行UPDATE语句。

You'd have to use actual key names from your dictionaries, of course. 当然,您必须使用词典中的实际键名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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