python sqlite插入命名参数或null

use*_*185 14 python sqlite named-parameters

我正在尝试使用命名参数将字典中的数据插入数据库.我有一个简单的SQL语句,例如

SQL = "INSERT INTO status (location, arrival, departure) VALUES (:location, :arrival,:departure)"
dict = {'location': 'somewhere', 'arrival': '1000', 'departure': '1001'}
c.execute(SQL,dict)
Run Code Online (Sandbox Code Playgroud)

在某处插入到位,1000到达到达列,1001到入境列.

我实际拥有的数据将包含位置,但可能包含到达或离开但可能不包含两者(在这种情况下,任何一个或NULL都不能进入表中).在这种情况下,我得到sqlite3.ProgrammingError:你没有提供绑定2的值.

我可以通过使用defaultdict解决这个问题:

c.execute(SQL,defaultdict(str,dict))
Run Code Online (Sandbox Code Playgroud)

为了使事情稍微复杂一些,我实际上会有一个包含多个位置的字典列表,其中包含到达或离开.

    ({'location': 'place1', 'departure': '1000'},
    {'location': 'palce2', 'arrival': '1010'},
    {'location': 'place2', 'departure': '1001'})
Run Code Online (Sandbox Code Playgroud)

我希望能够用c.executemany运行它,但我现在不能使用defaultdict.

我可以循环遍历列表中的每个字典并运行许多c.execute语句,但executemany似乎是一种更为简洁的方法.

为方便起见,我简化了这个示例,实际数据在字典中有更多条目,我从JSON文本文件构建它.

任何人对我如何做到这一点都有任何建议?

Mar*_*ers 15

使用None插入NULL:

dict = {'location': 'somewhere', 'arrival': '1000', 'departure': None}
Run Code Online (Sandbox Code Playgroud)

您可以使用默认字典和生成器将其用于executemany():

defaults = {'location': '', 'arrival': None, 'departure': None}

c.executemany(SQL, ({k: d.get(k, defaults[k]) for k in defaults} for d in your_list_of_dictionaries)
Run Code Online (Sandbox Code Playgroud)