python 读取sqlite存入文件_从SQLite的BLOB写入到文件使用Python

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

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

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值