且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-02 18:20:18

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

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)