使用 Python 将数组传递给 Firebird 数据库

Passing an array to a Firebird database using Python

我需要向 Firebird 2.5 数据库写入一个列表,其中包含:[-0.09143443, 0.09187854, -0.0907896, ...] 根据使用指南 FDB 1.7 执行所有操作:

import fdb

con = fdb.connect(dsn='localhost:/temp/test.db', user='sysdba', password='materkey')

cur = con.cursor()

arrayIn = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9,10,11,12]
  ]

print ('arrayIn:  %s' % (arrayIn))
cur.execute("insert into FACE_REC (ID, ARRAY) values (?, ?)", ('5', arrayIn))

cur.execute("select a from FACE_REC")
arrayOut = cur.fetchone()[0]
print ('arrayOut: %s' % (arrayOut))

con.commit()

之后我得到一个错误:

TypeError: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

在数据库字段 ARRAY 类型中:BLOB 大小 - 4096,子类型 - 文本。

请告诉我如何将这个列表写入数据库以及我应该使用什么类型的字段?

A blob sub_type text 不是数组数据类型,它是字符串数据类型。在将数组传递给 execute 之前,您需要将数组转换为合适的字符串表示形式。这也意味着您需要在检索时将字符串表示形式转换回数组。

Firebird 也有一个数组数据类型,但这不是很好支持,但 FDB 似乎支持这个。如果你真的想要或需要使用数组,你也可以尝试将你的列声明为数组类型。鉴于显示的数据,您需要将列声明为 integer[3,4],如 FDB 2.0 文档的 Firebird ARRAY datatype 部分所示:

import fdb

con = fdb.connect(dsn='localhost:/temp/test.db', user='sysdba', password='pass')
con.execute_immediate("recreate table array_table (a int[3,4])")
con.commit()

cur = con.cursor()

arrayIn = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9,10,11,12]
  ]

print 'arrayIn:  %s' % arrayIn
cur.execute("insert into array_table values (?)", (arrayIn,))

cur.execute("select a from array_table")
arrayOut = cur.fetchone()[0]
print 'arrayOut: %s' % arrayOut

con.commit()

您似乎将该代码用作代码示例的基础,但您似乎错过了列数据类型的声明(请参阅顶部附近的 recreate table 语句)。

但是,Firebird 对数组的支持非常有限,最好避免使用它。