1. 程式人生 > 實用技巧 >MySQL 5.7及8.0版本資料庫的root密碼遺忘的解決辦法

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