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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17425523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:09:53  来源:igfitidea点击:

Python MySQL OperationalError: 1045, "Access denied for user root@'localhost'

pythonmysql

提问by Max Kim

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

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

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

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

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

回答by Rohit Jain

You can try adding GRANT OPTIONat the end:

您可以尝试在最后添加GRANT OPTION

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';

Also See:

另见

回答by Noam Rathaus

I suggest to everyone to always use mysql_setpermissionrather than direct MySQL statements, mysql_setpermissiondoes everything for you including FLUSHing. Any other way is prone to mistakes.

我建议大家总是使用mysql_setpermission而不是直接的 MySQL 语句,mysql_setpermission为你做所有的事情,包括 FLUSHing。任何其他方式都容易出错。