MySQL 5.7及8.0版本数据库的root密码遗忘的解决办法


MySQL5.7破解root密码,跳过密码认证登录到数据库,直接修改表中的密码即可,但是MySQL 8.0则不可以这样修改root密码,需要跳过密码认证登录到数据库后,先将root密码设置为空,然后才可以登录到数据库,修改root密码。

一、遗忘MySQL 5.7数据库的root密码解决办法

① 方法一(推荐)

[root@db01 ~]# systemctl stop mysqld
[root@db01 ~]# mysqld --user=root --skip-grant-tables
 #使用mysqld指令启动mysql服务,跳过授权表
#上述命令执行后,会一直占用当前终端,需要再开启一个终端
#也不要想着放到后台运行了,放到后台3306端口不会监听的
[root@db01 ~]# netstat -anpt | grep 3306
tcp6       0      0 :::3306                 :::*                    LISTEN      4244/mysqld  
#确认端口正在监听
[root@db01 ~]# mysql -uroot
#直接使用root用户登录,无需密码
mysql> update mysql.user set authentication_string=password('123456') where user='root' and host='localhost';
#更改密码
mysql> flush privileges;
#刷新权限
[root@db01 ~]# kill 4244   
 #将之前mysqld启动时占用的终端进程号kill掉,切忌不要使用-9选项
[root@db01 ~]# systemctl start mysqld
[root@db01 ~]# mysql -uroot -p123456
mysql>

如果上面的过程中,使用kill -9来结束mysqld占用的终端,那么再次启动可能会报错,sock文件被锁定,此时,需要将你mysql的sock文件删除掉,再次启动MySQL即可!

② 方法二

[root@db01 ~]# vim /etc/my.cnf
[mysqld]      #在mysqld这行下写入下面内容
skip-grant-tables
[root@db01 ~]# systemctl restart mysqld
[root@db01 ~]# mysql -uroot
mysql> update mysql.user set authentication_string = password('pwd@123') where user = 'root';
mysql> flush privileges;     #刷新权限
[root@db01 ~]# vim /etc/my.cnf
[mysqld] 
skip-grant-tables            #删除此行
[root@db01 ~]# systemctl restart mysqld
[root@db01 ~]# mysql -uroot -ppwd@123

二、遗忘MySQL 8.0数据库的root密码解决办法

[root@mysql01 ~]# mysql --version        #查看MySQL版本
mysql  Ver 8.0.18 for linux-glibc2.12 on x86_64 (MySQL Community Server - GPL)
[root@mysql01 ~]# vim /etc/my.cnf         #编辑主配置文件
[mysqld]      #在mysqld这行下写入下面内容
skip-grant-tables
            .................#省略部分内容
[root@mysql01 ~]# systemctl restart mysqld      #重启MySQL服务,使配置文件生效
[root@mysql01 ~]# mysql -uroot           #跳过密码验证,直接登录数据库
#将root密码设置为空
mysql> use mysql
mysql> update user set authentication_string='' where user = 'root';
mysql> flush privileges;
mysql> exit
#开启密码验证并重新登录数据库
[root@mysql01 ~]# vim /etc/my.cnf         #编辑主配置文件
[mysqld] 
skip-grant-tables            #删除此行
[root@mysql01 ~]# systemctl restart mysqld          #重启使更改生效
[root@mysql01 ~]# mysql -uroot            #直接登录数据库
mysql> alter user root@localhost identified by 'pwd@111';
mysql> flush privileges;
mysql> exit
#使用新密码进行登录测试
[root@mysql01 ~]# mysql -uroot -ppwd@111
*************** 当你发现自己的才华撑不起野心时,就请安静下来学习吧!***************
原文地址:https://www.cnblogs.com/lvzhenjiang/p/14197147.html