您现在的位置是:首页 > 解决连接MySQL时报"The server requested authentication method unknown to the client”错误

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

默认 2024-05-25 17:38 587人围观 来源:hangge
mysql  
简介mysql8.0与mysql5.0存在一些差异,经常在项目中遇到,这次是关于用户认证的。

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 这边已经可以成功连接数据库了。
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3cn0udci9ym88

文章评论