python - 使用行工厂将字典插入 SQLite 的 native 方法,如果可能的话,使用自动增长的列数

标签 python sqlite dictionary

详情请参阅 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/

相关文章:

python - 在 scipy 中计算成对距离时出现内存错误

firefox - 以编程方式访问浏览器历史记录

python - 如何检测字典中的任何元素是否发生变化?

python - 从字典列表中提取值

jQuery 影响与单击或悬停元素具有相同类的元素

python - 使用 Sphinx 转换为 HTML 时如何在 reStructuredText 中转义单引号

python - Blender 导出插件和 bl_idname

perl - DBD::SQLite:插入或更新 - 问题

python - 在列表列表中查找项目的索引

sql - 更新Sqlite中的join