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

后端 未结 9 569
野趣味
野趣味 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:46

    dictionary = {'id':123, 'name': 'Abc', 'address':'xyz'}    
    query = "insert into table_name " + str(tuple(dictionary.keys())) + " values" + str(tuple(dictionary.values())) + ";"
    cursor.execute(query)
    

    query becomes

    insert into table_name ('id', 'name', 'address') values(123, 'Abc', 'xyz');
    

提交回复
热议问题