Writing blob from SQLite to file using Python
笨拙的Python新手需要帮助。 我通过创建一个简单的脚本来弄乱,该脚本将二进制文件插入到SQLite数据库的博客字段中:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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文件,看看它是否有效。