使用Python将SQLite中的BLOB写入文件

14 投票
1 回答
27464 浏览
提问于 2025-04-16 02:07

一个对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()

现在我需要写一个脚本,去获取某个记录的blob字段内容,并把这个二进制blob写入到一个文件中。在我的情况下,我用SQLite数据库来存储.odt文档,所以我想把它们提取出来并保存为.odt文件。我该怎么做呢?谢谢!

1 个回答

37

这里有一个脚本,它的功能是读取一个文件,把它放进数据库,然后再从数据库中读取这个文件,最后把它写到另一个文件里:

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文件,看它是否也能正常工作。

撰写回答