[英]python sqlite3 executemany using multiple lists
背景:
因此,我有一个大数组,我正在从一个来源读取并尝试使用python(有效地)写入SQLite3。
目前,我使用默认格式:
cursor.executemany("INSERT into mytable1 VALUES(?,?,?)", my_arr.tolist())
现在我想扩展到几十万张桌子。 我希望能够执行以下操作(希望):
cursor.executemany("INSERT into ? VALUES(?,?,?)", TableNameList, my_arr.tolist())
问题:
我尝试在stackexchange中查找,但是可能错过了一些东西。
我尝试在Python SQLite文档中查找,但没有看到类似的内容。 我尝试了通用Google搜索。
首先,Python位。 假设my_arr
是某种二维数组,并且.tolist()
生成一个列表列表,是的,有一种方法可以向列表中的每一行添加元素:
result = [[a]+b for a,b in zip(TableNameList, my_arr.tolist()]
其次,SQL位。 不,您不能使用?
指定表名。 表名必须确实存在于SQL语句中。 我能提供给您的最好的方法是多次运行curssor.execute
:
for table, values in zip(TableNameList, my_arr):
c.execute("INSERT INTO %s VALUES (?, ?, ?)"%table, values)
但是,请注意是否信任TableNameList
的源。 在%s
使用不受信任的数据会导致SQL注入安全性缺陷。
示例程序:
import sqlite3
import numpy as np
import itertools
my_arr = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
TableNameList = 't1', 't1', 't2', 't3'
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('''CREATE TABLE t1 (c1, c2, c3)''')
c.execute('''CREATE TABLE t2 (c1, c2, c3)''')
c.execute('''CREATE TABLE t3 (c1, c2, c3)''')
## Insert a row of data
#c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
for table, values in itertools.izip(TableNameList, my_arr):
c.execute("INSERT INTO %s VALUES (?, ?, ?)"%table, values)
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.