mysql5.7忘记root密码

1、停止mysql服务
systemctl stop mysqld.service


2、编辑配置文件
vim /etc/my.cnf
#在[mysqld]下添加
skip-grant-tables


3、启动mysql服务,直接回车登陆
systemctl start mysqld.service
mysql -uroot -p

[root@mysql5 bin]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.34 MySQL Community Server (GPL)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> update user set authentication_string='' where user='root';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> quit
Bye
[root@mysql5 bin]# systemctl stop mysqld.service
[root@mysql5 bin]# vi /etc/my.cnf
[root@mysql5 bin]# systemctl start mysqld.service

再次登录数据库

[root@mysql5 ~]# mysql -u root -p
Enter password:
 在我们成功登陆数据库之后,原以为可以操作数据库了,但是当我们随机运行一个sql语句时(这里我是运行的"select * from user "),mysql命令窗口却提示:

ERROR 1820 (HY000): You must reset your password using ALTER USE statement before executing this statement.
在执行该语句之前,你必须通过 alter user 来修改密码

   看到这样的错误,我们第一时间会通过"alter user ‘用户名’@‘loaclhost’ identified by ‘修改的密码’; " 该语句来修改密码,但是执行该语句之后,又发现一个新的错误:

ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
您的密码太过于简单.

   哇这样太坑了吧,看到这里相信在座的各位心里面应该都快要崩溃了,感觉自己像是被玩耍了一下,但不要着急,心急吃不了热豆腐,咱们一步一步来将它们解决掉.

   首先我们重新执行更改用户密码语句

mysql>alter user  user() identified by '';   

这里注意,填写密码的时候满足8位并且尽量是混合密码(英文、下划线、数字)


这样的话会发现我们的密码修改成功了,咦刚才明明不行的,为什么现在却可以了(实际上,如果刚才报错的话是因为咱们设置的密码过于简单,而导致触发了Mysql的一个策略),不过虽然解决了,但是相信各位肯定有很多疑惑,不过不要急接着往下看

mysql> show  varialables like 'validate_password%';   //执行该语句

可以看到图片中的Variable_name和Value的参数,其中我们会发现有个数字8和Medium(中等)的值,接着在看它们对应的参数为validate_password_length(密码长度)和validate_password_policy(密码策略)

为什么简单密码不行,为什么六位数的密码不行,原因问题出现在这里,那么应该怎么样修改它们呢?

mysql> set global validate_password_policy=low;             //将密码级别改为弱
mysql> set global validate_password_length=6;                //将密码长度改为6


mysql> alter user  '用户名'@'localhost' identified by '123456'; //改密码方式一
mysql> alter user  USER()  identified by '123456';                 //改密码方式二


参考连接:https://blog.csdn.net/qq_42618394/article/details/103181778