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

时间:2010-07-31 17:42:02

标签: python sql sqlite binary blob

一个无能为力的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 个答案:

答案 0 :(得分:29)

这是一个脚本,它读取文件,将其放入数据库,从数据库中读取,然后将其写入另一个文件:

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文件,看它是否有效。