python - 使用 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 库的调用不正确)”
解决方案
推荐阅读
- text - 如何使用 Flutter 编写带有要点的段落?
- javascript - 在组合中使用 Object.assign() 时可以使用相同的函数名称吗?
- python - Django媒体未加载,静态文件工作
- linux - 查找linux中两个文件夹之间更改的行数
- sql - 将 SQL 转换为 eloquent
- .htaccess - .htaccess 中的多个条件重定向 301 和 404
- python - 使用 fsolve 查找 Python 中两个平均值相交所需的价格
- vhdl - VHDL在详细说明之前无法调用子程序“log2”
- node.js - Mongoose 查找数组字段包含数组中所有值的对象
- ios - 在资产库中播放音频