【发布时间】: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