python - python中的多维数组到数据库

标签 python arrays database list sqlite

我正在尝试找出一种将二维数组(使用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/

相关文章:

python - 在其他函数中使用 Split 参数

c - 如何创建指向 3 维数组的 2 维的指针?

php - 使用 $_POST += array() 作为默认值

arrays - 在 Postgres jsonb 列中查询数组对象

sql-server - 在服务器中创建数据库后建立新的 SQL 连接

python - 如何使用 SSL 创建 python websocket 并在其中使用 cookie?

javascript - 使用 Python 在 Selenium 中运行 javascript

python - DataFrame 有条件地组合列

python - 从数据文件启动 postgres 数据库服务器

android - Android监听mysql数据库变化的方法