详情请参阅 How can I get dict from sqlite query? , row_factory
有助于在查询 SQLite 数据库时获取 dict
:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute('create table test (a text, b text, c int)')
conn.execute('insert into test values (?, ?, ?)', ('hello', 2, 17))
for r in conn.execute('select * from test'):
print(dict(r))
# {'a': 'hello', 'b': '2', 'c': 17}
查询的结果直接是一个dict
,这有时非常有用。
问题:使用row_factory
是否也可以轻松地INSERT
直接将dict
插入数据库?
Here是部分解决方案:
d = {'a': 1, 'b': 2, 'c': 3}
conn.execute('insert into test ({}) values ({})'.format(','.join(d.keys()), ','.join(['?'] * len(d))), tuple(d.values()))
但它并不是真正的“Pythonic”。
是否有更简洁的方法将字典直接插入 SQLite 数据库,例如使用 row_factory
?
旁注:如果它还能“自动增长”表定义,那就太好了,即如果我插入 d = {'newkey': 1, 'b': 2, 'c': 3}
,它会自动向表格添加一个新列。
最佳答案
由于我在评论中提到的原因,如果不用您自己的写入数据库文件的方式替换 SQL 接口(interface),可能无法“本地”执行此操作,但肯定可以使此代码更有效正如您提到的“pythonic”:
def sqlify_list(string_iterable):
""" ('a', 'b', 'c') -> '(a, b, c)' """
return f'({",".join(string_iterable)})'
def insert_dict_into_table(conn, table_name, _dict):
conn.execute(
'insert into {table_name} {keys} values {replacement_fields}'.format(
table_name=table_name,
keys=sqlify_list(d), # dict.__iter__ yields the keys, so .keys() isn't necessary
replacement_fields=sqlify_list('?'*len(d)) # str.__iter__ yields characters, so ','.join('?'*5) is equivalent to ','.join(['?']*5)
),
d.values()
)
d = {'a': 1, 'b': 2, 'c': 3}
insert_dict_into_table(conn, 'test', d)
至于
it would be great that it would also "auto-grow" the table definition
据我所知,关系数据库通常不用于这种临时模式更改。也许将字典以 JSON 形式存储在数据库中会更简单?或者也许切换到像 MongoDB 这样的无模式数据库?
关于python - 使用行工厂将字典插入 SQLite 的 native 方法,如果可能的话,使用自动增长的列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61769744/