【问题标题】:Add list of values to a blob field in firebird using Python使用 Python 将值列表添加到 firebird 中的 blob 字段
【发布时间】:2016-06-04 19:41:54
【问题描述】:

我有一个我喜欢存储在我的 firebird 数据库中的项目列表。 到目前为止,我编写了以下代码

    Sens=278.3
    DSens=1.2
    Fc10=3.8
    Bw10=60.0
    Fc20=4.2
    Bw20=90.0

    ResultArray = (Sens,DSens,Fc10,Bw10,Fc20,Bw20,t6,t20,Nel,Nsub)
    con = fdb.connect(dsn="192.168.0.2:/database/us-database/usdb.gdb",  user="sysdba", password="#########")
    cur = con.cursor()
    InsertStatement="insert into Tosh_Probe (TestResults ) Values (?)"
    cur.execute(InsertStatement, (ResultArray,))                           
    con.commit()

在这里,TestResult 字段是我数据库中的 blob 字段。

这给出了一个 TypeError (???) 将这些值存储到 blob 中的正确语法是什么

我尝试的另一个选项是将项目列表写入 StringIO,并将其存储在数据库中。现在在数据库中创建了一个新条目,但没有数据添加到 blob 字段 这是将字段添加到 StringIO 的代码

    ResultArray = StringIO.StringIO()
    ResultArray.write = Sens
    ResultArray.write = DSens   
    #ResultArray.close #tried with and without this line but with the same result

【问题讨论】:

  • 您使用的是 fdb 还是其他驱动程序?您将元组作为值传递,这不是 blob 可接受的值。您需要将其转换为单个值(例如作为字符串或流)。 AFAIK StringIO 应该可以工作,但我有一段时间没有用 python 做任何事情了。
  • 是的,我正在使用 fdb 驱动程序。我知道我的列表不起作用,这就是为什么我尝试了 SrtingIO 但不知何故 blobfields 仍然是空的。
  • 现在我通过将我的值解析为逗号分隔的字符串并将其添加到 blob 字段来“解决”它,但不知何故这根本不令人满意,因为我只想将我的值解析为二进制格式的二进制流并将其添加到 blob 字段。我希望你们中的一些人能指引我正确的方向

标签: python blob firebird


【解决方案1】:

我已经使用 Python 3.5.1 和 FDB 1.6 对此进行了测试。以下是所有工作的变体(写入blob sub_type text):

import fdb
import io

con = fdb.connect(dsn='localhost:testdatabase', user='sysdba', password='masterkey')

cur = con.cursor()
statement = "insert into blob_test2 (text_blob) values (?)"
cur.execute(statement, ("test blob as string",))
cur.execute(statement, (io.StringIO("test blob as StringIO"),))
streamwrites = io.StringIO()
streamwrites.write("streamed write1,")
streamwrites.write("streamed write2,")
streamwrites.seek(0)
cur.execute(statement, (streamwrites,))

con.commit()

con.close()

在写入StringIO 的情况下,与您的代码的主要区别是:

  1. 使用write(...) 代替write = ...
  2. 使用seek(0) 将流定位在开头,否则您什么也读不到,因为流定位在最后一次写入之后。

我没有尝试过二进制 IO,但我希望它能够以类似的方式工作。

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 2010-10-20
    • 2012-02-13
    • 1970-01-01
    • 2022-06-14
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多