Laravel - 解决连接MySQL时报"The server requested authentication method unknown to the client”错误

 

1,问题描述

最近建了个 Laravel 项目,当配置好 MySQL 数据库进行请求时,页面报如下错误:
 
SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client (SQL: select * from user where id = 3)
Previous exceptions
  • SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client (2054)
  • PDO::__construct(): The server requested authentication method unknown to the client [caching_sha2_password] (0)
 

2,问题原因

(1)过去 MySQL 的密码认证插件是“mysql_native_password”。
(2)而当 mysql 到了 8.0 版以上时,密码认证插件使用的是“caching_sha2_password”。可是当前有很多数据库工具和链接包都不支持这个。
 

3,解决办法

修改密码认证方式,改回“mysql_native_password”认证插件。
 

4,操作步骤

(1)首先编辑 mysql 配置文件。由于我用的是 mac 电脑,安装后默认是没有这个配置文件的,执行如下命令添加配置文件:
1
sudo vi /etc/my.cnf

(2)按下 i 进入编辑模式,添加如下内容(把加密模式改成旧的):
1
2
[mysqld]
default_authentication_plugin=mysql_native_password

(3)最后按下 esc 退出编辑模式。 接着组合按下 shift + : 开启命令,然后输入 wq 回车,保存退出。
 
(4)由于原来创建的用户(比如 root)还是使用新的验证方式,我们还需将它们改成老的。首先使用命令行连接数据库:
1
mysql -u root -p

(5)登录后依次执行下面三个命令(其中密码部分根据情况自行修改):
1
2
3
ALTER USER  'root' @ 'localhost'  IDENTIFIED BY  '密码'  PASSWORD EXPIRE NEVER;
ALTER USER  'root' @ 'localhost'  IDENTIFIED WITH mysql_native_password BY  '密码' ;
FLUSH PRIVILEGES;

(6)完毕后重启 MySQL 服务可以发现,PHP 这边已经可以成功连接数据库了。


原文出自:www.hangge.com  转载请保留原文链接:https://www.hangge.com/blog/cache/detail_2331.html

猜你喜欢

转载自www.cnblogs.com/mouseleo/p/11900621.html