使用 Python 将 blob 从 SQLite 写入文件

Writing blob from SQLite to file using Python(使用 Python 将 blob 从 SQLite 写入文件)
本文介绍了使用 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)