適用場景
- 遺忘 Root 密碼
- 權限表損壞無法登入
- Windows / Linux 通用
步驟 1:編輯配置啟用 skip-grant-tables
# Windows: 安裝目錄\my.ini
# Linux: /etc/my.cnf
[mysqld]
skip-grant-tables
步驟 2:重啟服務
# Windows
net stop mysql
net start mysql
# Linux
systemctl restart mysqld
# 或 /etc/init.d/mysqld restart
步驟 3:免密登入並更新密碼
mysql -u root mysql
-- 5.7.6+ 使用 authentication_string 欄位
UPDATE user SET authentication_string = PASSWORD('7758521') WHERE User = 'root';
-- 5.7.6 前使用 Password 欄位
-- UPDATE user SET Password = PASSWORD('7758521') WHERE User = 'root';
FLUSH PRIVILEGES;
QUIT;
步驟 4:還原配置並重啟
# 刪除 skip-grant-tables 行
# 重啟服務
net stop mysql && net start mysql
# 或 systemctl restart mysqld
步驟 5:新密碼驗證
mysql -u root -p7758521
# 成功進入表示重置完成
MySQL 8.0 注意
ALTER USER 'root'@'localhost' IDENTIFIED BY '7758521';
-- 或
UPDATE mysql.user SET authentication_string = NULL WHERE User = 'root';
FLUSH PRIVILEGES;
-- 然後用 caching_sha2_password 重新設定
安全提醒
- `skip-grant-tables` 期間任何人可免密登入,內網環境亦需盡快完成
- 完成後必須移除該參數並重啟
- 建議同時檢查是否有匿名用戶、% 主機 root 等風險帳號