首页 > 解决方案 > PyMySQL 无法验证特定用户(MySQLdb 成功)

问题描述

使用相同的数据库凭据,MySQLdb 会成功进行身份验证,而 pymysql 则不会。这只发生在一个特定的用户身上。

>>> import pymysql
>>> import MySQLdb
>>> MySQLdb.connect(**creds)
<_mysql.connection open to 'xxx' at edeae8>
>>> pymysql.connect(**creds)
...
pymysql.err.OperationalError: (1045, "Access denied for user 'xxx'@'10.x.x.x' (using password: YES)")

有没有人知道可能导致这种情况的任何线索?是否知道 pymysql 会特别对待某些用户名?或者未能正确处理密码中的某些字符?

请注意,pymysql 可以使用其他凭据很好地连接:

>>> pymysql.connect(**other_creds)
<pymysql.connections.Connection object at 0x7f6991558240>
>>> MySQLdb.connect(**other_creds)
<_mysql.connection open to 'xxx' at edeae8>

需要明确的是,PyMySQL 失败的身份验证在我尝试过的所有其他方法中都成功,包括mysql使用相同凭据的客户端的命令行调用。

使用 Python 3.5.2

标签: python-3.xpymysql

解决方案


差不多两年后,但无论如何我都会在这里留下答案

此错误在https://github.com/PyMySQL/PyMySQL/issues/804中报告,标记为“不是错误”并关闭。Pymysql 是唯一不为您转义字符的库,因此您需要在使用之前将字符串转换为字节,如下所示:

import pymysql.cursors
connection = pymysql.connect(host='127.0.0.1',
                             user='root',
                             password=bytes('my-sécrét-pw', 'utf-8') ,
                             db='dbase')

推荐阅读