INSERT字典sqlite3(python) [英] INSERT dictionary sqlite3 (python)
问题描述
sqlite的新功能,并且语法麻烦。
New to sqlite and having trouble with the syntax.
我需要遍历字典的每个键,并将dict [key]插入与字典键相同名称的列中。如果它有任何差异,dict ['Url']包含主键,并且所有的行都已经创建。
I need to iterate through each key of a dictionary and insert dict[key] into the column with the same name as the dictionary key. If it makes any difference, dict['Url'] contains the primary key, and all the rows are already created.
到目前为止,我想我已经目睹了一切可能OperationalError。
$ b
So far I think I've witnessed every possible OperationalError.
for key in merged_dict:
cur.execute("INSERT INTO Games VALUES (?,?)", (key, merged_dict[key]))
推荐答案
命名参数:
cur.execute("INSERT INTO GAMES (key1, key2, key3, key4) VALUES (:key1, :key2, :key3, :key4)",
merged_dict)
将从字典中获取名称的参数,但这些键 do 必须存在。要支持可能不存在的键(默认为 NULL
,请使用无缺少的 defaultdict
对象键:
This will take parameters by name from a dictionary, but those keys do have to exist. To support keys that may not exist (defaulting them to NULL
instead, use a defaultdict
object that will use None
for missing keys:
from collections import defaultdict
params = defaultdict(lambda: None, merged_dict)
cur.execute("INSERT INTO GAMES (key1, key2, key3, key4) VALUES (:key1, :key2, :key3, :key4)",
params)
这篇关于INSERT字典sqlite3(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!