Jeffrey Froman
Jeffrey Froman

Reputation: 6623

PyMySQL fails to authenticate specific user (MySQLdb succeeds)

Using the same database credentials, MySQLdb succeeds at authentication while pymysql does not. This happens only for one specific user.

>>> 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)")

Does anyone have any clues as to what might be causing this? Is pymysql known to treat certain usernames specially? Or fail to handle certain characters in passwords appropriately?

Note that pymysql can connect just fine using other credentials:

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

To be clear, the authentication that fails with PyMySQL succeeds with all other methods I've tried, including a command-line invocation of the mysql client using the same credentials.

Using Python 3.5.2

Upvotes: 1

Views: 1361

Answers (2)

zincr0
zincr0

Reputation: 11

Almost two years later but i will leave the answer here anyway

This bug was reported in https://github.com/PyMySQL/PyMySQL/issues/804, marked as "not a bug" and closed. Pymysql is the only library that doesn't escape characters for you, so you need to convert your string to bytes before using it, like this:

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

Upvotes: 1

Chris Johnson
Chris Johnson

Reputation: 21976

You need to URL encode the password if it contains any characters that conflict with the database URL format. The @ you mentioned in comments would have this problem.

This can be done via urllib.urlencode or equivalent.

Upvotes: 1

Related Questions