从SQLite的BLOB写入到文件使用Python [英] Writing blob from SQLite to file using Python

查看:2805
本文介绍了从SQLite的BLOB写入到文件使用Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个无能的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字段的内容和二进制数据写入一个文件的脚本。就我而言,我使用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.

这篇关于从SQLite的BLOB写入到文件使用Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆