1.停止你正在運作的mysql
方法一:指令行:net stop mysql
方法二:任務管理器 --> 服務 --> mysql右鍵關閉
2.管理者身份運作cmd,輸入
mysqld --shared-memory --skip-grant-tables
注:mysqld --skip-grant-tables這個指令8.0以上已經失效
此時這個視窗就不能動了,以管理者身份運作打開一個新視窗

ff8335a70b0a28bd966fb635edbb417.png
3.在新視窗cd到目前目錄 ,鍵入
mysql -uroot -p
密碼不用輸入,直接回車過去,如圖:

d380acb7817f72ba99510f959b7da2b.png
4.輸入 use mysql;,進入mysql
5.輸入置空密碼指令
update user set authentication_string='' where user='root';
注:8.0以上版本 ‘password’ 字段已經不管用了,會報錯,相關的指令比如:update mysql.user set password='newpassword' where user='root';一同失效

301f92b6c3038890b9389dd9b8e2f42.png
6.輸入設定新密碼指令
alter user 'root'@'localhost' identified by '設定的新密碼'
7.必填:flush privileges;
這個時候可能報錯:The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement;
解決:重新整理權限表:flush privileges;

a7913cb6354dba2015d0894fc20a6c6.png
8.Ctrl+Z退出mysql,重新運作,使用新密碼登入,完成
mysql -h localhost -u root -p

53eb9bee0cf41f8ab14dacbe75ff4d2.png
9.如果使用navicat連接配接資料庫時報錯2059,原因是mysql8 之前的版本中加密規則是mysql_native_password,而在mysql8之後,加密規則是caching_sha2_password,我們在這裡修改一下加密規則就好了
mysql -h localhost -u root -p //登入
use mysql; //選擇資料庫
ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER; //更改加密方式
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的密碼'; //更新使用者密碼
FLUSH PRIVILEGES; //重新整理權限
再ps:上邊連結的方法試了一下,第八步指令需要敲雙引号,不然會報錯