2014-02-17 82 views
1

我想找出一种方法来将二维数组(使用python)放入sqlite数据库。我的阵列:多维数组到python数据库

['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) 

回答

1

使用cursor.executemany() method一气呵成插入行的序列:

query_string = 'INSERT INTO sample VALUES (?, ?, ?)' 

c.executemany(query_string, array2d) 
conn.commit() 

不要忘记conn.commit()交易。

为了演示的目的,我还没有为格式化SQL参数而烦恼,您无论如何都不想这么做,因为您的列数固定不变(来自CREATE TABLE定义)。

+0

感谢您的回复。我摆脱了错误信息,但是当使用SQLite数据库浏览器查看sample.db时,数据字段为空。 – David

+0

您还需要提交。 :-) –

+0

当然可以。谢谢。 – David