錯誤 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) 通常因密碼遺忘、權限表損壞、Host 不匹配導致。本文提供 Windows 官方 --init-file 法、通用 --skip-grant-tables 法、Debian/Ubuntu 專用 debian.cnf 法三大方案,覆蓋 99% 場景。
--init-file 法(推薦生產環境)C:\mysql-init.txt,單行寫入:SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPassword');C:\mysql\bin\mysqld-nt --init-file=C:\mysql-init.txtmysql-init.txt,正常重啟服務。--skip-grant-tables 法(Linux/Windows 通用)# 1. 停止服務
systemctl stop mysqld # Linux
net stop mysql # Windows 服務
# 2. 跳過授權表啟動(需加 --skip-networking 防外部連入)
mysqld_safe --skip-grant-tables --skip-networking &
# 3. 免密登錄修改密碼
mysql -u root mysql
UPDATE user SET authentication_string=PASSWORD('newpass') WHERE User='root';
FLUSH PRIVILEGES;
QUIT
# 4. 正常重啟
mysqladmin -u root -p shutdown
systemctl start mysqld
MySQL 5.7+ 注意:密碼列改為 authentication_string,舊版為 Password。
debian.cnf 法(無需停機)Debian 系安裝會自動生成維護帳號 debian-sys-maint,密碼存於 /etc/mysql/debian.cnf。
# 讀取密碼
cat /etc/mysql/debian.cnf
# [client]
# user = debian-sys-maint
# password = xxxxxxxxxxxxxxxx
# 直接登錄修改 root 密碼
mysql -u debian-sys-maint -p'xxxxxxxxxxxxxxxx'
UPDATE mysql.user SET authentication_string=PASSWORD('newpass') WHERE User='root';
FLUSH PRIVILEGES;
QUIT
優勢:無需停機、無需跳過授權、不影響業務連接。
mysqladmin 直接改密# 停止服務後 d:\mysql\bin\mysqld-nt --skip-grant-tables # 新開 CMD d:\mysql\bin\mysqladmin -u root flush-privileges password "newpassword" # 重啟服務
SELECT User, Host, plugin FROM mysql.user; 確認 root@localhost 存在且 plugin 為 mysql_native_password(或 caching_sha2_password)。mysql -uroot -p'newpass' -e "SELECT 1;" 驗證連通性。三大方案任選其一,均能在 5 分鐘內恢復 root 訪問。建議平時將密碼存入密碼管理器,並為應用帳號單獨分配最小權限,避免直接使用 root。