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

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

    There is a solution for using dictionaries. First, the sql-statement

    INSERT INTO Media VALUES (NULL, 'x');
    

    would not work, as it assumes you are referring to all columns, in the order they are defined in the CREATE TABLE statement, as abarnert stated. (See SQLite INSERT.)

    Once you have fixed it by specifying the columns, you can use named placeholders to insert data. The advantage of this is that is safely escapes key-characters, so you do not have to worry. From the Python sqlite-documentation:

    values = {'title':'jack', 'type':None, 'genre':'Action', 'onchapter':None,'chapters':6,'status':'Ongoing'}
    cur.execute('INSERT INTO Media (id, title, type, onchapter, chapters, status) VALUES (:id, :title, :type, :onchapter, :chapters, :status);'), values)
    

提交回复
热议问题