1、修改配置文件跳过权限检查
编辑 MySQL 配置文件 my.cnf
,在 [mysqld]
配置节点添加 skip-grant-tables
配置:
[mysqld]
skip-grant-tables
2、重启 MySQL 服务
service mysqld restart
3、修改密码
此时终端用 mysql
命令登录时不需要用户密码:
mysql -u root
-------------
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.36 MySQL Community Server (GPL)
mysql>
然后我们可以使用以下两种方式修改密码:
1)使用 set password
命令(8.0 版本之后弃用):
mysql> SET PASSWORD FOR 'root'@'%' = PASSWORD('123456');
2)更新 mysql.user
表:
-- mysql 5.7 版本之前(不含5.7)
UPDATE `mysql`.`user` SET `password`=PASSWORD('123456') WHERE `user`='root';
-- mysql 5.7 版本之后(包含5.7)
UPDATE `mysql`.`user` SET `authentication_string`=PASSWORD('123456') WHERE `user`='root';
-- 密码修改生效
FLUSH PRIVILEGES;
4、还原权限检查配置
编辑 MySQL 配置文件 my.cnf
,在 [mysqld]
配置节点删除 skip-grant-tables
配置,然后重启 MySQL 服务即可恢复密码验证登录。