只要擁有作業系統的 root 或管理員權限,即可透過跳過權限表啟動 MySQL,進而重置密碼。以下步驟適用於 Linux/Unix 環境(Windows 請參考官方文件)。
killall -TERM mysqld
若使用 systemd:systemctl stop mysqld。
mysqld_safe --skip-grant-tables &
此模式下不檢查權限表,任何人可無密碼登入。建議同時加上 --skip-networking 防止遠程連線。
mysql -u root
USE mysql;
UPDATE user SET authentication_string=PASSWORD('新密碼') WHERE User='root';
FLUSH PRIVILEGES;
EXIT;
注意:MySQL 5.7+ 欄位為 authentication_string,5.6 及之前為 Password。若使用 mysql_native_password 外掛,亦可用 ALTER USER 'root'@'localhost' IDENTIFIED BY '新密碼';。
killall -TERM mysqld
systemctl start mysqld # 或 service mysqld start
現在即可用新密碼正常登入。
--skip-grant-tables 參數。skip-grant-tables 僅在本機啟動時生效,並限制網路存取。FLUSH PRIVILEGES; 已執行;檢查 user.Host 欄位是否包含 localhost、127.0.0.1、::1 等實際連線來源。net stop mysql,再以 mysqld --skip-grant-tables 啟動,後續步驟相同。