繁体   English   中英

使用字典列表更新表

[英]Update table using a list of dictionaries

我有一个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.

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

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

这可能吗? 或者我应该看一个替代方法,如插入临时表等?

sqlite3数据库适配器以以下形式获取命名参数:keyname 结合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)

对于dictrows列表中的每个字典,查询将字典中的键值value1value2key1key2作为SQL参数,并执行UPDATE语句。

当然,您必须使用词典中的实际键名。

暂无
暂无

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

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