我正在尝试找出一种将二维数组(使用Python)放入sqlite数据库中的方法。我的数组:
['hello', 'hello', 'hello'], ['hello', 'hello', 'hello']
我想要的是每个“hello”元组都有一个新行,每个“hello”都是其自己的属性。我不确定我正在尝试做的事情是否可能(我希望如此)。我尝试关注其他一些帖子,但不断收到错误:
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
有谁知道如何将多维数组插入到sqlite数据库中?任何帮助,将不胜感激。这是我的代码:
import sqlite3
array2d = [['hello' for x in xrange(3)] for x in xrange(3)]
var_string = ', '.join('?' * len(array2d))
conn = sqlite3.connect('sample.db')
c = conn.cursor()
c.execute('''CREATE TABLE sample (Name TEXT, Line_1 TEXT, Line_2 TEXT)''')
query_string = 'INSERT INTO sample VALUES (%s);' % var_string
c.execute(query_string, array2d)
最佳答案
使用cursor.executemany()
method一次性插入一系列行:
query_string = 'INSERT INTO sample VALUES (?, ?, ?)'
c.executemany(query_string, array2d)
conn.commit()
不要忘记 conn.commit()
事务。
为了演示目的,我没有费心在这里格式化 SQL 参数;无论如何,您实际上不想在这里这样做,因为您的列数是固定的(来自 CREATE TABLE
定义)。
关于python - python中的多维数组到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21839697/