啟動 MySQL 時若遇到 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) 錯誤,通常是因為 root 密碼未正確設定或遺失。本文提供一套經實測有效的重置流程,幫助您快速恢復資料庫存取權限。
嘗試以 root 身分登入 MySQL 時:
[root@www ~]# mysql -u root -p Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
核心概念是先關閉 MySQL 服務,以 --skip-grant-tables 模式啟動(不載入權限表),進入資料庫後直接更新 mysql.user 表中的 root 密碼,最後重新啟動服務生效。
[root@www ~]# service mysqld stop Stopping mysqld: [ OK ]
[root@www ~]# mysqld_safe --skip-grant-tables &
此時可直接無密碼登入:
[root@www ~]# mysql -u root Welcome to the MySQL monitor...
mysql> USE mysql;
mysql> UPDATE user SET authentication_string=PASSWORD('新密碼') WHERE User='root' AND Host='localhost';
Query OK, 1 row affected (0.01 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
mysql> \q
注意:MySQL 5.7+ 版本密碼欄位為authentication_string,舊版為password。若報錯請依版本調整欄位名。
[root@www ~]# service mysqld restart [root@www ~]# mysql -u root -p Enter password: Welcome to the MySQL monitor...
host 欄位是否為 localhost、127.0.0.1 或 %,必要時新增對應主機記錄。FLUSH PRIVILEGES 失敗,可嘗試 mysql_upgrade 修復系統表。依照上述流程操作,即可徹底解決 root 登入被拒的問題,恢復資料庫正常存取。