执行pymysql.connect时出现错误Keyerror 255

时间:2017-07-28 08:17:45

标签: python mysql pymysql

这是代码

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

错误Traceback是:

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,无论传递的是非null charset参数。

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

3 个答案:

答案 0 :(得分:4)

要扩展上述仅限链接的答案,请考虑对当前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

请注意在上面的行缩进中包含隐藏的标签。

<强>参考

答案 1 :(得分:1)

可以参考这个问题 Pull Request 591

答案 2 :(得分:0)

但你的变量在哪里?

import pymysql

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