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

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

    I was having the similar problem so I created a string first and then passed that string to execute command. It does take longer time to execute but mapping was perfect for me. Just a work around:

    create_string = "INSERT INTO datapath_rtg( Sr_no"
    for key in record_tab:
        create_string = create_string+ " ," + str(key)
    create_string = create_string+ ") VALUES("+ str(Sr_no) 
    for key in record_tab:
        create_string = create_string+ " ," + str(record_tab[key])
    create_string = create_string + ")"
    cursor.execute(create_string)
    

    By doing above thing I ensured that if my dict (record_tab) doesn't contain a particular field then the script wont throw out error and proper mapping can be done which is why I used dictionary at the first place.

提交回复
热议问题