Python MySQL OperationalError: 1045, "访问被拒绝用户 root@'localhost'

问题描述:

我试图通过以下方式从我的 python 程序访问数据库:

I was trying to access the database from my python program by:

db = mysql.connect(host = 'localhost', user = 'Max', passwd = 'maxkim', db = 'TESTDB')
cursor = db.cursor()

但是,我在第一行代码中收到一条错误消息.

But, I get an error message in the first line of code.

OperationalError: (1045, "Access denied for user 'Max'@'localhost' (using password: YES)")

为了解决这个问题,我做了以下事情:

To remedy the situation, I did the following:

$ mysql -u Max-p
Enter password: maxkim

mysql> create database TESTDB;
mysql> grant usage on *.* to Max@localhost identified by ‘maxkim’;
mysql> grant all privileges on TESTDB.* to Max@localhost ;
mysql> exit

如果我已经为用户Max"(我)授予了对数据库的所有访问权限,为什么我仍然不能在 python 中连接?

If I have granted all access to the the database for the user "Max" (me), why can't I still connect in python?

您可以尝试在末尾添加 GRANT OPTION :

You can try adding GRANT OPTION at the end:

GRANT all privileges on TESTDB.* to 'Max'@'localhost' IDENTIFIED BY 'maxkim' WITH GRANT OPTION;

您还可以使用以下命令查找用户的授权:

You can also use the below command to find the grants for a user:

SHOW GRANTS FOR 'Max'@'localhost';

另见: