Python Sqlite3: INSERT INTO table VALUE(dictionary goes here)

后端 未结 9 588
野趣味
野趣味 2020-12-24 12:26

I would like to use a dictionary to insert values into a table, how would I do this?

import sqlite3

db = sqlite3.connect(\'local.db\')
cur = db.cursor()

c         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 12:31

    Here's a more generic way with the benefit of escaping:

    # One way. If keys can be corrupted don't use.
    sql = 'INSERT INTO demo ({}) VALUES ({})'.format(
                ','.join(my_dict.keys()),
                ','.join(['?']*len(my_dict)))
    
    # Another, better way. Hardcoded w/ your keys.
    sql = 'INSERT INTO demo ({}) VALUES ({})'.format(
                ','.join(my_keys),
                ','.join(['?']*len(my_dict)))
    
    cur.execute(sql, tuple(my_dict.values()))
    

提交回复
热议问题