【问题标题】:How do I write a BLOB, any BLOB to sqlite?我如何写一个 BLOB,任何 BLOB 到 sqlite?
【发布时间】:2019-10-02 01:17:10
【问题描述】:

我需要使用 Python 2.7 将 Obj-C 对象(例如本例中的 NSString)写入 sqlite 数据库并将其存储在 BLOB 列中。 在这种情况下,我编写了这个演示代码,但由于以下回溯而失败。

    from sqlite3 import connect
    from Foundation import NSArchiver

    conn = connect(':memory:')
    create = "CREATE TABLE test(data BLOB)"
    conn.execute(create)
    conn.commit()

    blob = NSArchiver.archivedDataWithRootObject_("Hello World").bytes()
    print type(blob), blob
    sql = "INSERT INTO test VALUES (?)"
    data = [blob]

    conn.execute(sql, data)
    conn.commit()

这可以追溯到:

    $ ./sqlite3_test.py
    <type 'memoryview'> <memory at 0x104a5e218>
    Traceback (most recent call last):
      File "./sqlite3_test.py", line 16, in <module>
        conn.execute(sql, data)
    sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

使用sqlite3.Binary(在 sqlite3 模块中定义为Binary = buffer)或.tobytes()(来自memoryview)的任何magik 都无法使这项工作变得更好。

我还尝试从 NSArchiver blob 中创建一个 buffer() 对象,但这是一种天真的方法:

b = buffer(blob, 0, len(blob))

追溯到TypeError: buffer object expected - 可以说 NSArchiver 对象不是 Python 字符串。

【问题讨论】:

  • 如果您使用的是 Objective C,您可能可以使用原生 Sqlite C 接口,因此使用 blob api(在 INSERT 中使用 zeroblob() 函数,然后使用 C 函数填写你想要的数据。

标签: objective-c python-2.7 sqlite pyobjc


【解决方案1】:

我有一个工作示例! 在 Objective-C 调用 bytes() 上,我需要调用 memoryview .tobytes(),然后可以将其序列化为 buffer()

#!/usr/bin/python -tt

from sqlite3 import connect, Binary
from Foundation import NSArchiver

conn = connect(':memory:')
create = "CREATE TABLE test(data BLOB)"
conn.execute(create)
conn.commit()

str = NSString.alloc().initWithString_("Hello World")
blob = NSArchiver.archivedDataWithRootObject_(str).bytes().tobytes()
print "Original (%s): %s" % (len(blob), blob)
sql = "INSERT INTO test VALUES (?)"
data = [Binary(blob)]

conn.execute(sql, data)
conn.commit()

cursor = conn.cursor()
cursor.execute("SELECT * FROM test")
rows = cursor.fetchall()
for r in rows:
    print "In database (%s): %s" % (len(r[0]), r[0])

这给出了:

$ ./sqlite3_test.py 
Original (84):
   streamtyped???@???OC_PythonString?NSString?NSObject??i?+
                                                                Hello World?
In database (84):
   streamtyped???@???OC_PythonString?NSString?NSObject??i?+
                                                                Hello World?

【讨论】:

    猜你喜欢
    • 2012-08-07
    • 2015-05-25
    • 2011-08-16
    • 2019-10-22
    • 2014-04-07
    • 2022-01-04
    • 1970-01-01
    • 2015-02-26
    • 2012-04-14
    相关资源
    最近更新 更多