首先,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
. 在 a 中使用不受信任的数据%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()