Access denied for user 'root'@'localhost' (using password: YES) 是 MySQL 最經典的錯誤。本文提供三條經實戰驗證的重置密碼路徑:Windows 官方 --init-file 方案、Linux 通用 --skip-grant-tables 方案、Debian/Ubuntu 專屬 debian-sys-maint 維護賬號方案,並附贈「免密登錄配置」長效機制。
services.msc → 停止 MySQL;或任務管理器結束 mysqld.exe。C:\mysql-init.txt,單行內容:SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPassword');
C:\mysql\bin\mysqld-nt --init-file=C:\mysql-init.txt
net start mysql。mysql -u root -pMyNewPassword。# 1. 停止服務
systemctl stop mysqld
# 或 /etc/init.d/mysql stop
# 2. 跳過權限表啟動(後台運行)
mysqld_safe --user=mysql --skip-grant-tables --skip-networking &
# 3. 另開終端,免密登入
mysql -u root mysql
# 4. 更新密碼並刷新權限
UPDATE user SET authentication_string=PASSWORD('newpassword') WHERE User='root';
FLUSH PRIVILEGES;
QUIT;
# 5. 重啟服務
systemctl restart mysqld
# 6. 新密碼驗證
mysql -u root -pnewpassword
關鍵點:
--skip-networking 防止跳過權限期間外部連入,安全第一。authentication_string,5.6 為 Password,視版本調整。plugin 列建議設置為 mysql_native_password。Debian 系安裝 MySQL 自動創建維護賬號,密碼存於 /etc/mysql/debian.cnf。
# 1. 讀取密碼
cat /etc/mysql/debian.cnf
# [client]
# user = debian-sys-maint
# password = xxxxxxxx
# 2. 使用維護賬號登入
mysql -u debian-sys-maint -p
# 輸入上述密碼
# 3. 修改 root 密碼
UPDATE mysql.user SET authentication_string=PASSWORD('newpassword') WHERE User='root';
FLUSH PRIVILEGES;
QUIT;
# 4. 驗證
mysql -u root -pnewpassword
優勢:無需停服務、無需跳過權限、極低風險。
# 1. 管理員 CMD 結束進程 taskkill /f /im mysqld-nt.exe # 2. 啟動跳過權限 d:\mysql\bin\mysqld-nt --skip-grant-tables # 3. 另開 CMD 重置密碼 d:\mysql\bin\mysqladmin -u root flush-privileges password "newpassword" # 4. 重啟服務 net start mysql
編輯 ~/.my.cnf (Linux) / my.ini (Windows):
[client] user=root password=your_strong_password host=localhost
設置文件權限 chmod 600 ~/.my.cnf。之後直接 mysql 登錄,腳本自動化無需明文傳密碼。
| 場景 | 推薦路徑 | 理由 |
|---|---|---|
| Windows 生產環境 | 路徑一 --init-file | 官方標準、無需跳過權限、安全合規 |
| Linux 通用/無 debian.cnf | 路徑二 --skip-grant-tables | 最通用、版本無關 |
| Debian/Ubuntu 系統 | 路徑三 debian-sys-maint | 零停機、零風險、最快 |
| 自動化腳本/長期運維 | 配置 .my.cnf 免密登錄 | 消除密碼管理負擔 |
收藏此文,下次遇到 1045 不再慌亂,按圖索驥 5 分鐘搞定。