首页 > 解决方案 > 使用 Python 从 mySQL 读取 BLOB 文件

问题描述

首先,我是数据库应用程序的新手。我正在尝试从 mySQL 数据库接收 BLOB 文件;目前正在尝试运行我从网站上找到的 python 代码块。我能够成功地将 BLOB 文件加载到数据库中,但是我没有收到我上传的 BLOB 文件。这是python代码。

import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode

def write_file(data, filename):
    # Convert binary data to proper format and write it on Hard Disk
        with open(filename, 'wb') as file:
            file.write(data)
def readBLOB(emp_id, photo):
        print("Reading BLOB data from python_employee table")
        try:
            connection = mysql.connector.connect(user='***', password='***',
                          host='******',
                          database='*****')
            cursor = connection.cursor(prepared=True)
            sql_fetch_blob_query = """SELECT * from faceimages where id = %s"""
            cursor.execute(sql_fetch_blob_query, (emp_id, ))
            record = cursor.fetchall()
            for row in record:
                print("Id = ", row[0] )
                print("Name = ", row[1])
                image =  row[2]
                print("Storing employee image and bio-data on disk \n")
                write_file(image, photo)
               #write_file(file, bioData)
        except mysql.connector.Error as error :
            connection.rollback()
            print("Failed to read BLOB data from MySQL table {}".format(error))
        finally:
            #closing database connection.
            if(connection.is_connected()):
                cursor.close()
                connection.close()
                print("MySQL connection is closed")
readBLOB(1, '/home/can/Desktop/photo.jpg')

预期的结果应该是:

Reading BLOB data from python_employee table
Id = 1
Name = Eric
Storing employee image and bio-data on disk
MySQL connection is closed

我的结果如下:

Reading BLOB data from python_employee table
Id =  1
Name =  bytearray(b'Eric')
Storing employee image and bio-data on disk     
MySQL connection is closed

该代码会创建一个 .jpg 文件,但无法加载该文件。

“无法加载图像“photo.jpg”。”
“解释 JPEG 图像文件时出错(在状态 201 中对 JPEG 库的调用不正确)”

标签: pythonmysqlfileblob

解决方案


推荐阅读