python sqlite insert named parameters or null

后端 未结 2 987
谎友^
谎友^ 2021-02-19 01:54

I\'m trying to insert data from a dictionary into a database using named parameters. I have this working with a simple SQL statement e.g.

SQL = \"INSERT INTO sta         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 02:34

    Use None to insert a NULL:

    dict = {'location': 'somewhere', 'arrival': '1000', 'departure': None}
    

    You can use a default dictionary and a generator to use this with 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)
    

提交回复
热议问题