从字典值中插入表字段值和相应的键

时间:2015-07-28 15:09:36

标签: python dictionary sqlite database-table

是否可以将字典值一次一个地插入到sqlite3数据库表的特定字段/列中? 字段/列是在上一步中使用数据库创建的。

我更喜欢使用for循环,但我还没找到合适的sqlite3"命令"选择与字典键相同的列,并插入相应的值(字典值)。

import sqlite3

with sqlite.connect(db_full_path) as connection:
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM {}".format(db_table))
    db_fields = ','.join('?' for tab in cursor.description) # i.e. ?,?,?,?

    cursor.executemany("INSERT INTO {} VALUES ({})"\
        .format(db_table, db_fields), (ORDERED_DATA_VALUES,))
    connection.commit()

' cursor.execute'和' cursor.executemany'两者都需要一个预定义数量的列和一个按正确顺序排列相同数量的项目的排序列表,我认为这对我来说不太理想。

我更喜欢迭代字典并一次插入一个值,但是插入同一行:

for key, value in NOT_ORDERED_DATA_VALUES.items():
     # insert value into corresponding field/column (key)

0 个答案:

没有答案
相关问题