Windows 環境
1. 停止服務
net stop mysql

2. 跳過權限表啟動
mysqld --skip-grant-tables

3. 新開 CMD 視窗重置密碼
mysql -uroot
UPDATE mysql.user SET authentication_string=PASSWORD('新密碼') WHERE User='root';
FLUSH PRIVILEGES;

4. 重啟服務驗證
net start mysql
mysql -uroot -p新密碼
Linux 環境
1. 停止 MySQL
killall -TERM mysqld
2. 跳過權限啟動
mysqld_safe --skip-grant-tables &
3. 重置密碼
mysql -u root
USE mysql;
UPDATE user SET authentication_string=PASSWORD('新密碼') WHERE User='root';
FLUSH PRIVILEGES;
4. 正常重啟
killall -TERM mysqld
systemctl start mysqld # 或 service mysqld start
MySQL 5.7+ 注意事項
- 密碼欄位從
password 改為 authentication_string
PASSWORD() 在 8.0 已移除,建議用:
ALTER USER 'root'@'localhost' IDENTIFIED BY '新密碼';
- 若
--skip-grant-tables 啟動,FLUSH PRIVILEGES 後才能執行 ALTER USER
安全建議
- 重置後立即執行
mysql_secure_installation
- 禁止 root 遠端登入:
UPDATE user SET Host='localhost' WHERE User='root';
- 建立專用業務帳號,最小權限原則
- 定期輪換密碼、審計帳號