適用版本:MySQL 5.1 / 5.5 / 5.6 / 5.7 (Windows)。核心原理:啟動時跳過權限表檢查 (`--skip-grant-tables`),以免密碼登入,更新 `mysql.user` 表重置密碼,再正常重啟服務。
⚠️ 安全警示: `--skip-grant-tables` 會暫時移除所有認證授權,**任何人可無密碼連線並擁有最高權限**。執行期間請:
net stop mysql (或服務管理器停止)。cd "C:\Program Files\MySQL\MySQL Server 5.1\bin"mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server 5.1\my.ini" --console --skip-grant-tables
mysql -u root -p
Enter password: (直接按 Enter)
USE mysql;
UPDATE user SET Password = PASSWORD('NewStrongPass123!') WHERE User = 'root';
FLUSH PRIVILEGES;
QUIT;
MySQL 5.7+ `Password` 欄位改為 `authentication_string`,語法:UPDATE user SET authentication_string = PASSWORD('...') WHERE User='root'; 或 ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPass'; (需權限表生效,故仍需 skip-grant-tables 先用 UPDATE)。
net start mysqlmysql -u root -p → 輸入新密碼 → 登入成功。| 現象 | 原因 | 解決 |
|---|---|---|
| 視窗 1 閃退 | 路徑錯誤、my.ini 遺失、埠被佔用 | 檢查路徑、改用 `--console` 看錯誤輸出、`netstat -ano | findstr 3306` |
| 視窗 2 連線失敗 "Can't connect" | 視窗 1 mysqld 未就緒、埠不對、命名管道/共享記憶體衝突 | 等待視窗 1 顯示 "ready for connections"、指定 `--protocol=tcp --port=3306` |
| UPDATE 0 rows affected | User 非 'root'、Host 不匹配 (如 'root'@'127.0.0.1') | SELECT User, Host FROM user; 確認確切 Host,WHERE 條件加上 Host |
| 密碼修改後仍無法登入 | 未執行 FLUSH PRIVILEGES、未正常重啟服務、快取舊密碼 | 必須 FLUSH PRIVILEGES、關閉 skip-grant-tables 進程、net start mysql 正常啟動 |