python读取mysql数据库blob类型_用python中的mysql连接器正确获取mysql数据库中的blob...

我复制了上面的错误:Traceback (most recent call last):

File "demo.py", line 16, in

cursor.execute(query, ())

return codecs.utf_8_decode(input, errors, True)

UnicodeDecodeError: 'utf8' codec can't decode byte '0xff ... '

in position 0: invalid start byte

使用版本:

^{pr2}$

使用python代码#!/usr/bin/python

# -*- coding: utf-8 -*-

import mysql.connector

conn = mysql.connector.connect(

user='asdf',

password='asdf',

host='1.2.3.4',

database='the_db',

connect_timeout=10)

cursor = conn.cursor(buffered=True) #error is raised here

try:

query = ("SELECT data_blob FROM blog.cmd_table")

cursor.execute(query, ())

except mysql.connector.Error as err: #error is caught here

#error is caught here, and printed:

print(err) #printed thustly

使用python的open(填充的python变量“raw byte binary”如下:def read_file_as_blob(filename):

#r stands for read

#b stands for binary

with open(filename, 'rb') as f:

data = f.read()

return data

所以问题就在文件中数据的编码转换(mysql blob的数据编码)和mysql如何提取blob并将其转换回utf-8之间。在

两种解决方案:

解决方案1正如AHalvar所说,设置use_pure=True参数并传递给mysql.connector.connect( ... )。神秘的是,它真的起作用了。但是优秀的程序员会注意到,遵从神秘咒语是一种不好的代码气味。布朗运动的修正会招致技术债务。在

解决方案2是尽早和经常地对数据进行编码,防止双重重新编码和双重数据解码,这是这些问题的根源。尽快将其锁定为通用的编码格式。在

对我来说,令人满意的解决方案是在这个过程的早期强制utf-8编码。到处执行UTF-8。在data.encode('UTF-8')

unicode文件堆代表了我对在不同操作系统和编码方案上的不同设备之间进行字符编码的这种临时照顾的看法。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值