使用 Python 将 blob 从 SQLite 写入文件
毫无头绪的 Python 新手需要帮助.我创建了一个简单的脚本,将二进制文件插入到 SQLite 数据库的博客字段中,这让我感到困惑:
A clueless Python newbie needs help. I muddled through creating a simple script that inserts a binary file into a blog field in a SQLite database:
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
input_note = raw_input(_(u'Note: '))
input_type = 'A'
input_file = raw_input(_(u'Enter path to file: '))
with open(input_file, 'rb') as f:
ablob = f.read()
f.close()
cursor.execute("INSERT INTO notes (note, file) VALUES('"+input_note+"', ?)", [buffer(ablob)])
conn.commit()
conn.close()
现在我需要编写一个脚本来获取特定记录的 blob 字段的内容并将二进制 blob 写入文件.在我的例子中,我使用 SQLite 数据库来存储 .odt 文档,所以我想抓取它们并将它们保存为 .odt 文件.我该怎么做?谢谢!
Now I need to write a script that grabs the contents of the blob field of a specific record and writes the binary blob to a file. In my case, I use the SQLite database to store .odt documents, so I want to grab and save them as .odt files. How do I go about that? Thanks!
推荐答案
这是一个脚本,它确实读取文件,将其放入数据库,从数据库中读取,然后将其写入另一个文件:
Here's a script that does read a file, put it in the database, read it from database and then write it to another file:
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
with open("...", "rb") as input_file:
ablob = input_file.read()
cursor.execute("INSERT INTO notes (id, file) VALUES(0, ?)", [sqlite3.Binary(ablob)])
conn.commit()
with open("Output.bin", "wb") as output_file:
cursor.execute("SELECT file FROM notes WHERE id = 0")
ablob = cursor.fetchone()
output_file.write(ablob[0])
cursor.close()
conn.close()
我用 xml 和 pdf 对其进行了测试,它运行良好.用你的 odt 文件试试看它是否有效.
I tested it with an xml and a pdf and it worked perfectly. Try it with your odt file and see if it works.
相关文章