首页 > 解决方案 > mysql.connector 不允许我将 gzip 压缩数据上传到数据库

问题描述

我正在尝试在 Python 中压缩文件,将此数据上传到 MySQL 数据库,然后在 C# 中下载/解压缩。这是我压缩文件的方式:

from gzip import GzipFile
from io  import BytesIO

def gzip_str(data):
   sio = BytesIO()
   with GzipFile(fileobj=sio, mode='wb') as gzip:
       gzip.write(data)

       return sio.getvalue()        

然后将文件上传到数据库,执行类似于:

import mysql.connector as mysql

cnx = mysql.connect(**config)
cursor = cnx.cursor()

data = gzip_str( open("filepath.csv", "rb").read() )

cursor.execute("INSERT INTO table (data) VALUES (%s)", (data))
cnx.commit()

我收到错误消息DatabaseError: Invalid utf8mb4 character string: '8B0800'。压缩 gzip 数据的标头以开头,\x8b\x08\x00&因此似乎无法将其识别为有效的 utf8mb4 字符。有没有办法解决这个问题?我需要这个头文件完整,以便它正确解压缩。该列data具有类型LONGBLOB,因此我什至不确定为什么无论如何都需要对其进行编码,我不应该只存储字节数据吗?

标签: pythonc#mysql-connectormysql-connector-python

解决方案


推荐阅读