使用 Python 将 Blob 从 SQLite 写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3379166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:44:05  来源:igfitidea点击:

Writing blob from SQLite to file using Python

pythonsqlsqlitebinaryblob

提问by dmpop

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:

一个笨手笨脚的 Python 新手需要帮助。我通过创建一个简单的脚本将二进制文件插入到 SQLite 数据库的博客字段中:

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()

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!

现在我需要编写一个脚本来获取特定记录的 blob 字段的内容并将二进制 blob 写入文件。就我而言,我使用 SQLite 数据库来存储 .odt 文档,因此我想抓取它们并将其保存为 .odt 文件。我该怎么做?谢谢!

采纳答案by Eric Fortin

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()

I tested it with an xml and a pdf and it worked perfectly. Try it with your odt file and see if it works.

我用 xml 和 pdf 对其进行了测试,效果很好。用您的 odt 文件尝试一下,看看它是否有效。