Python:如何将字典插入到 sqlite 数据库中?

2021-12-08 00:00:00 python dictionary sqlite

我有一个带有以下列表的 sqlite 数据库:

I have a sqlite database with a table with following columns :

id(int) , name(text) , dob(text)

我想插入以下字典:

{"id":"100","name":"xyz","dob":"12/12/12"}

字典键是列名.我怎样才能实现它?

Dictionary keys are the column names. How can i achieve it ?

推荐答案

这是一种保持参数安全的方法.(可能需要在表名部门打磨)

Here's a way which preserves parameter safety. (Might need polishing in the tablename department)

def post_row(conn, tablename, rec):
    keys = ','.join(rec.keys())
    question_marks = ','.join(list('?'*len(rec)))
    values = tuple(rec.values())
    conn.execute('INSERT INTO '+tablename+' ('+keys+') VALUES ('+question_marks+')', values)

row = {"id":"100","name":"xyz","dob":"12/12/12"}
post_row(my_db, 'my_table', row)

相关文章