MySQL登录时出现 Access denied for user 'root'@'xxx.xxx.xxx.xxx' (using password: YES) 的原因及解决办法

场景一:调试web程序访问数据库的时候出现

场景二:MySQL登陆的时候,区分本地localhost登陆,以及远程登陆。即使本地能够登陆,如果不授权也无法远程登陆

分析原因:(区分)当本地出现这样的情况,就是密码错误,找到正确的密码或者修改密码;当远程登陆的时候,首先确定登陆密码是否正确,第二确定是否远程授权。针对以上两种情况,给出解决方案。

情况一解决方案:修改本地数据库密码

方法1: 用SET PASSWORD命令 
首先登录MySQL。 
格式:mysql> set password for 用户名@localhost = password('新密码'); 
例子:mysql> set password for root@localhost = password('123'); 

方法2:用mysqladmin 
格式:mysqladmin -u用户名 -p旧密码 password 新密码 
例子:mysqladmin -uroot -p123456 password 123 

方法3:用UPDATE直接编辑user表 
首先登录MySQL。 
mysql> use mysql; 
mysql> update user set password=password('123') where user='root' and host='localhost'; 
mysql> flush privileges; 

方法4:在忘记root密码的时候,可以这样 
以windows为例: 
1. 关闭正在运行的MySQL服务。 
2. 打开DOS窗口,转到mysqlin目录。 
3. 输入mysqld --skip-grant-tables 回车。--skip-grant-tables 的意思是启动MySQL服务的时候跳过权限表认证。 
4. 再开一个DOS窗口(因为刚才那个DOS窗口已经不能动了),转到mysqlin目录。 
5. 输入mysql回车,如果成功,将出现MySQL提示符 >。 
6. 连接权限数据库: use mysql; 。 
6. 改密码:update user set password=password("123") where user="root";(别忘了最后加分号) 。 
7. 刷新权限(必须步骤):flush privileges; 。 
8. 退出 quit。 
9. 注销系统,再进入,使用用户名root和刚才设置的新密码123登录。

情况二解决方案 :远程授权

1. 先用localhost登录(进入MySQL)      mysql -u root -p
Enter password:  (输入密码)
2. 执行授权命令
mysql> grant all privileges on *.* to root@'%' identified by '123';  (注意语句后面的“;”)
Query OK, 0 rows affected (0.07 sec)
3. 退出再试:  mysql> quit
4、再试登录:    mysql -u root -h 192.168.194.142 -p
  Enter password: 
 结果显示:Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 3
表示成功


下面详细说说如何给用户授权。
 
mysql> grant 权限1,权限2, ... 权限n on 数据库名称.表名称 to 用户名@用户地址 identified by '连接口令';

权限1,权限2,... 权限n 代表 select、insert、update、delete、create、drop、index、alter、grant、references、reload、shutdown、process、file 等14个权限。
当权限1,权限2,... 权限n 被 all privileges 或者 all 代替时,表示赋予用户全部权限。
当 数据库名称.表名称 被 *.* 代替时,表示赋予用户操作服务器上所有数据库所有表的权限。
用户地址可以是localhost,也可以是IP地址、机器名和域名。也可以用 '%' 表示从任何地址连接。
'连接口令' 不能为空,否则创建失败。

举几个例子:
mysql> grant select,insert,update,delete,create,drop on vtdc.employee to joe@10.163.225.87 identified by ‘123′;
给来自10.163.225.87的用户joe分配可对数据库vtdc的employee表进行select,insert,update,delete,create,drop等操作的权限,并设定口令为123。

mysql> grant all privileges on vtdc.* to joe@10.163.225.87 identified by ‘123′;
给来自10.163.225.87的用户joe分配可对数据库vtdc所有表进行所有操作的权限,并设定口令为123。

mysql> grant all privileges on *.* to joe@10.163.225.87 identified by ‘123′;
给来自10.163.225.87的用户joe分配可对所有数据库的所有表进行所有操作的权限,并设定口令为123。

mysql> grant all privileges on *.* to joe@localhost identified by ‘123′;
给本机用户joe分配可对所有数据库的所有表进行所有操作的权限,并设定口令为123。案:远程授权

原文地址:https://www.cnblogs.com/zwq194/p/11534078.html