Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将python字典收集到sqlite3中_Python_Dictionary_Sqlite - Fatal编程技术网

将python字典收集到sqlite3中

将python字典收集到sqlite3中,python,dictionary,sqlite,Python,Dictionary,Sqlite,情景: SQLite3数据库中的一个表有14列。 15本字典,有不同数量的键10-14。 表中列的每个键都有一个包含400个元素的列表值,即每个列表值的元素5将位于第5行。 我需要将这些字典中的数据插入到前面提到的表中,考虑到一些字典不会使用表中的所有14列 最有效的方法是什么?假设您的数据已经是sql安全的,并且每个dict的键都足以插入一行: import sqlite3 from itertools import izip, repeat conn = sqlite3.connect('

情景:

SQLite3数据库中的一个表有14列。 15本字典,有不同数量的键10-14。 表中列的每个键都有一个包含400个元素的列表值,即每个列表值的元素5将位于第5行。 我需要将这些字典中的数据插入到前面提到的表中,考虑到一些字典不会使用表中的所有14列


最有效的方法是什么?

假设您的数据已经是sql安全的,并且每个dict的键都足以插入一行:

import sqlite3
from itertools import izip, repeat

conn = sqlite3.connect('mydb.sqlite3')
table_name = 'test'
cursor = conn.cursor()

# Create test table.
cursor.execute('DROP TABLE IF EXISTS {}'.format(table_name));
cursor.execute('CREATE TABLE {} (a1 integer, a2 integer, a3 integer)'.format(table_name));
conn.commit()

my_dicts = [
    { 'a1': repeat(1, 5), 'a2': repeat(2, 5), 'a3': repeat(3, 5) },
    { 'a2': repeat(4, 2) },
    { 'a3': repeat(7, 7) },
]

for my_dict in my_dicts:
    # Key <=> Items order has to be preserved.
    # .keys() and .values() not used to be sure
    # the order is preserved.
    keys = []
    items = []
    for k, v in my_dict.iteritems():
        keys.append(k)
        items.append(v)

    sql = "INSERT INTO {} ({}) VALUES ({})".format(table_name, ','.join(keys), ','.join(repeat('?', len(keys))))
    cursor.executemany(sql, izip(*items))
    conn.commit()

cursor.execute('SELECT * FROM {}'.format(table_name));
conn.commit()

>>> print cursor.fetchall()
[(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (None, 4, None), (None, 4, None), (None, None, 7), (None, None, 7), (None, None, 7), (None, None, 7), (None, None, 7), (None, None, 7), (None, None, 7)]

谢谢你的回复。我尝试了此操作并收到:Traceback最近的调用last:File./test_func.py,第75行,在cursor.executemanysql,izip*items sqliter3.interfaceeerror:Error binding参数0-可能不受支持的类型。您能给出一个数据示例和创建表的sql吗?它是在Python脚本中使用cursor.execute创建的。我已验证数据库和表是否已创建。它拥有id作为主键,然后是整数/文本列。就数据而言,它是使用pandas.read_CSV从CSV文件中检索的。示例字典是:my_dict.get'one'。。。[1,2,3,4,5,6,7,8,9,...,400]. 同样,我在创建字典后验证了字典。您是否认为问题在于数据而不是SQL格式?添加了示例,您能否确认我的数据与您的数据格式相同?