忘記 MySQL root 密碼是 DBA 常見場景。MySQL 官方提供標準流程:停止服務 → 跳過授權表啟動 → 無密碼登入 → 更新密碼 → 正常重啟。本文詳細記錄每步指令與關鍵參數說明。
mysql.server stop
# 或 systemctl stop mysqld
# 或 service mysql stop
mysqld_safe --skip-grant-tables --skip-networking &
--skip-grant-tables:跳過權限檢查,允許無密碼登入--skip-networking:禁用 TCP/IP 連線,**安全關鍵**,防止外部無授權存取&:背景執行mysql -u root
USE mysql;
-- MySQL 5.7.6+ / 8.0+
UPDATE user SET authentication_string = PASSWORD('新密碼') WHERE User = 'root';
-- MySQL 5.7.6 之前
UPDATE user SET Password = PASSWORD('新密碼') WHERE User = 'root';
關鍵:MySQL 5.7.6 將 `password` 欄位改名為 `authentication_string`,請依版本選擇正確欄位。
FLUSH PRIVILEGES;
EXIT;
mysqladmin shutdown
# 等待進程結束
mysql.server start
# 或 systemctl start mysqld
net stop mysql 或服務管理員cd "C:\Program Files\MySQL\MySQL Server 5.x\bin"
mysqld --skip-grant-tables --skip-networking
mysql -u rootCtrl+C 結束 mysqld 進程,再 net start mysql| 版本 | 密碼欄位 | 啟動腳本 | 備註 |
|---|---|---|---|
| 5.0 - 5.7.5 | Password | mysqld_safe / safe_mysqld | 舊版腳本名 safe_mysqld |
| 5.7.6+ | authentication_string | mysqld_safe | 密碼欄位重命名 |
| 8.0+ | authentication_string | mysqld_safe | 預設 caching_sha2_password 插件 |
-- 8.0 預設 caching_sha2_password,舊客戶端可能不支援
UPDATE user SET plugin = 'mysql_native_password'
WHERE User = 'root';
FLUSH PRIVILEGES;
-- 建立 init-file.sql
ALTER USER 'root'@'localhost' IDENTIFIED BY '新密碼';
-- 啟動時載入
mysqld --init-file=/path/to/init-file.sql --skip-networking &
更安全,不需跳過授權表,但需檔案系統寫入權限。
mysql -u root -p'新密碼' -e "SELECT VERSION();"
# 成功連線並顯示版本號即表示重置成功
遵循官方標準流程,配合版本差異處理與安全防護,即可安全快速完成 MySQL root 密碼重置。