问题描述
不确定sqlite.Binary
您使用的是什么,但是无论如何,这是一个有效的示例:
import sqlite3
# let's just make an arbitrary binary file...
with open('/tmp/abin', 'wb') as f:
f.write(''.join(chr(i) for i in range(55)))
# ...and read it back into a blob
with open('/tmp/abin', 'rb') as f:
ablob = f.read()
# OK, Now for the DB part: we make it...:
db = sqlite3.connect('/tmp/thedb')
db.execute('CREATE TABLE t (thebin BLOB)')
db.execute('INSERT INTO t VALUES(?)', [buffer(ablob)])
db.commit()
db.close()
# ...and read it back:
db = sqlite3.connect('/tmp/thedb')
row = db.execute('SELECT * FROM t').fetchone()
print repr(str(row[0]))
使用Python 2.6运行时,此代码将按预期和期望显示:’\ x00 \ x01 \ x02 \ x03 \ x04 \ x05 \ x06 \ x07 \ x08 \ t \ n \ x0b \ x0c \ r \ x0e \ x0f \ x10 \ x11 \ x12 \ x13 \ x14 \ x15 \ x16 \ x17 \ x18 \ x19 \ x1a \ x1b \ x1c \ x1d \ x1e \ x1f!“#$%&'()* +,-。/ 0123456’
请注意,需要使用buffer
插入blob并将str
其作为字符串读回(因为它也使用了该buffer
类型)-如果您只是要将其写入磁盘,则不需要后面的段落(因为write
文件方法的确像接受字符串一样接受缓冲区对象)。
解决方法
我正在尝试编写一个简单的Python脚本,该脚本将.odt文档插入到SQLite数据库中。这是我到目前为止所做的,但是似乎没有用:
f=open('Loremipsum.odt','rb')
k=f.read()
f.close()
cursor.execute="INSERT INTO notes (note) VALUES ('%s')" %(sqlite.Binary(k))
cursor.close()
conn.close()
我没有收到任何错误消息,但据我发现未插入记录。我究竟做错了什么?另外,如何提取回存储的文档?谢谢!