python - 执行pymysql.connect时报错Keyerror 255

标签 python mysql pymysql

这是代码

import pymysql
pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='iDontWannaSay',
    db='iDontWannaShow',
    charset='utf8'
)

错误回溯是:

data is :::::b'\xff\x02\x00\xff\x81\x15'....##### I was add near line 1279 which is print("data is :::::%s...."%data[i:i+6])
Traceback (most recent call last):
  File "C:\Users\123\Desktop\pymysqldebug.py", line 8, in <module>
    charset='utf8'
  File "D:\Program Files (x86)\Python\Python35\lib\site-packages\pymysql\__init__.py", line 90, in Connect
    return Connection(*args, **kwargs)
  File "D:\Program Files (x86)\Python\Python35\lib\site-packages\pymysql\connections.py", line 709, in __init__
    self.connect()
  File "D:\Program Files (x86)\Python\Python35\lib\site-packages\pymysql\connections.py", line 934, in connect
    self._get_server_information()
  File "D:\Program Files (x86)\Python\Python35\lib\site-packages\pymysql\connections.py", line 1279, in _get_server_information
    self.server_charset = charset_by_id(lang).name
  File "D:\Program Files (x86)\Python\Python35\lib\site-packages\pymysql\charset.py", line 39, in by_id
    return self._by_id[id]
KeyError: 255

似乎 struct.unpack 方法将 '\xff\' 解析为 255 并分配给 self.server_language,无论传递的非空字符集参数如何。

这是MySQL版本问题吗?(version 8.0.1-dmr)

最佳答案

要扩展上述仅接受链接的答案,请考虑对当前的 pymysql 安装进行以下更改。对于 MySQL 8,mysql-python API 无法识别可能较新的字符集,因此会引发 KeyError

要解决此问题,请在该目录中找到的 pymysql 模块下找到 connectors.py 脚本:

print(pymysql.__file__)

备份原始 connectors.py 脚本。然后合并以下更改。

原创(第 1268-1269 行)

self.server_language = lang
self.server_charset = charset_by_id(lang).name  

替换 (第 1268 - 1272 行)

self.server_language = lang
try:
    self.server_charset = charset_by_id(lang).name
except KeyError:
    self.server_charset = None

小心将隐藏的标签包含在上面几行的缩进中。

引用

关于python - 执行pymysql.connect时报错Keyerror 255,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45368336/

相关文章:

python - Gtk:如何在带有与整个文件相关的滚动条的 TextView 中获取文件的一部分

mysql - 使用内部查询中的列名选择要在外部查询中显示的列

python - 如何在 Python 中获取主窗口的句柄?

python - 对具有滞后的列求和的最快方法

mysql - Angularjs + Nodejs + mysql

php - 从数据库中获取最新条目

Python:为与 mysql 的拒绝数据库连接创建异常

python - 使用 PyMySQL,我无法连接到 RDS

python - 如何在 forms.Form 子类上动态设置 models.ModelChoiceField 的查询集

php - 座位预订不起作用