0

代码:

import mysql.connector
import sys

def write_file(data, filename):
    with open(filename, 'wb') as f:
        f.write(data)

sampleNum = 0;
db_config = mysql.connector.connect(user='root', password='test',
                      host='localhost',
                      database='technical')
# query blob data form the authors table
cursor = db_config.cursor()

try:
    sampleNum=sampleNum+1;
    query = "SELECT fileAttachment FROM document_control WHERE id=%s"
    cursor.execute(query,(sampleNum,))
    file = cursor.fetchone()[0]
    write_file(file, 'User'+str(sampleNum)+'.docx')


except AttributeError as e:
    print(e)
finally:
    cursor.close()

它能做什么

上面的代码 - 从存储为 a 的 MySQL 获取文件,并将文件BLOB保存.docx到文件夹中。

问题

但不是保存它,而是查看它然后删除它。我可以简单地打开BLOBin word 而不保存它吗?

如果是这样,怎么办?

4

1 回答 1

1

BLOB通常,可以使用内置模块将像实体这样的二进制数据作为类文件对象传递io,例如:

import io

f = io.BytesIO(data)
# f now can be used anywhere a file-object is expected

但您的问题实际上更多地归结为 MS Word 能够打开未保存在磁盘上任何位置的文件的能力。我不认为它可以做到这一点。最佳做法可能是使用 生成一个临时文件tempfile,这样您至少可以期望系统最终会清理它:

import tempfile

with tempfile.NamedTemporaryFile(suffix='.docx', delete=False) as f:
    f.write(data)
    print(f.name)

编辑:

特别是在您的代码中,您可以尝试以下方法将数据存储在临时文件中并在 MS Word 中自动打开它:

import tempfile, subprocess

WINWORD_PATH = r'C:\Program Files (x86)\Microsoft Office\Office14\winword.exe'

def open_as_temp_docx(data):
    with tempfile.NamedTemporaryFile(suffix='.docx', delete=False) as f:
        f.write(data)
    subprocess.Popen([WINWORD_PATH, f.name])
cursor = db_config.cursor()

try:
    sampleNum=sampleNum+1;
    query = "SELECT fileAttachment FROM document_control WHERE id=%s"
    cursor.execute(query,(sampleNum,))
    open_as_temp_docx(cursor.fetchone()[0])

我手头没有装有 MS Word 的 Windows 机器,所以我无法对此进行测试。您机器上的路径winword.exe可能会有所不同,因此请确保它是正确的。

编辑:

如果在 MS Word 关闭后立即删除文件很重要,则以下操作应该有效:

import tempfile, subprocess, os

WINWORD_PATH = r'C:\Program Files (x86)\Microsoft Office\Office14\winword.exe'

def open_as_temp_docx(data):
    with tempfile.NamedTemporaryFile(suffix='.docx', delete=False) as f:
        f.write(data)
    subprocess.Popen([WINWORD_PATH, f.name]).wait()
    if os.path.exists(f.name):
        os.unlink(f.name)
于 2019-12-20T14:12:15.687 回答