如何将多行从python嵌套字典插入sqlite数据库

时间:2018-12-28 18:46:38

标签: python dictionary data-structures sqlite

我读取了一个yaml文件并将值提取到python列表中。我想将值转储到sqlite数据库中,并且列表的结构是嵌套的。我尝试了各种将数据存储在数据库中的方法,如下所示,但它们不能解决问题。

当格​​式为('a','b','c')的列表能够插入表格时,不会出现问题。但是当我有一个键值对时,就会遇到问题。

Data structure: 
 [   {   'CPU': 2,
    'jobname': 'Job1',
    'memory': '4 GB',
    'problem': 'Prob1',
    'team': '1'},
{   'CPU': 4,
    'jobname': 'Job2',
    'memory': '256 GB',
    'problem': 'Prob3',
    'team': '3'},
{   'CPU': 5,
    'jobname': 'Job3',
    'memory': '8 GB',
    'problem': 'Prob5',
    'team': '1'}]

这是我尝试过的方法,但看起来它们的数据结构略有不同:Python : How to insert a dictionary to a sqlite database?

# read data from the config file
def read_yaml(file):
    with open(file, "r") as stream:
        try:
            config = yaml.safe_load(stream)
        except yaml.YAMLError as exc:
            print(exc)
            print("\n")
    return config

    q = read_yaml("queue.yaml")

  # establish connection to sqlite database and save into db
 conn = sqlite3.connect('queues.db')
 c = conn.cursor()

 # create a sqlite3 database to store the dictionary values
 def create_table():
    c.execute("CREATE TABLE IF NOT EXISTS queues(job TEXT, team 
       TEXT, problem TEXT, CPU INT, memory TEXT)")

 create_table()

 # insert data into the table
def dynamic_data_entry():
    for item in q:
        c.execute("INSERT INTO queues VALUES (?, ?, ?, ?, ?)", item)
    conn.commit()

dynamic_data_entry()

这是输出错误:追溯(最近一次呼叫过去):

File "queue_info.py", line 50, in <module>
dynamic_data_entry()
File "queue_info.py", line 47, in dynamic_data_entry
c.execute("INSERT INTO queues VALUES (?, ?, ?, ?, ?)", item)
sqlite3.ProgrammingError: Binding 1 has no name, but you supplied a 
 dictionary (which has only names).

1 个答案:

答案 0 :(得分:1)

sqlite3使用占位符语法:[key]代替?支持dictionaries。 您也可以使用executemany代替for item in q:

c.executemany("INSERT INTO queues (job, team, problem, CPU, memory) VALUES
    (:jobname, :team, :problem, :CPU, :memory);", data)