使用PyMySQL连接MySQL 8.0时出现unpack requires a buffer of 4 bytes错误
解决PyMySQL连接MySQL8.0时的"unpack requires a buffer of 4 bytes"错误
可能的原因及解决方案
1. 升级PyMySQL到兼容MySQL8.0的版本
旧版本PyMySQL对MySQL8.0的通信协议支持不完善,会触发字节解析错误。执行以下命令升级:
pip install --upgrade PyMySQL
2. 修改连接字符集为utf8mb4
MySQL8.0中推荐使用utf8mb4作为字符集(原生utf8仅支持3字节Unicode,存在局限性),调整连接参数:
import pymysql con = pymysql.Connect( host='localhost', port=3306, user='root', password='123456', db='test', charset='utf8mb4' # 替换原有的utf8 ) cur = con.cursor() sql1 = 'select * from student' cur.execute(sql1) data = cur.fetchall() cur.close() con.close() for i in data: print(str(i))
3. 调整MySQL用户的认证插件
MySQL8.0默认使用caching_sha2_password认证插件,部分旧版PyMySQL不支持该插件。可将用户认证方式改为mysql_native_password:
- 打开MySQL Workbench登录后,执行SQL命令:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456'; FLUSH PRIVILEGES;
- 重启MySQL服务后,重新运行Python代码。
内容的提问来源于stack exchange,提问作者Muhammad
相关产品推荐
相关产品推荐

