1045 - Access denied for user 'root'@'localhost' (using password: YES)
原因:用戶名或密碼錯誤,MySQL 拒絕連接。不想重裝數據庫時,需通過跳過權限驗證重置密碼。
# 系統服務管理方式可能不同,嘗試以下命令 /etc/init.d/mysql stop # 或 /etc/init.d/mysqld stop # 或 systemd systemctl stop mysqld # 確認進程已停 ps -ef | grep mysql
# 後台運行,輸出重定向到 /dev/null /usr/local/mysql/bin/mysqld_safe --skip-grant-tables >/dev/null 2>&1 & # 若路徑不同,用 find 定位 find / -name mysqld_safe 2>/dev/null
關鍵參數:--skip-grant-tables 使 MySQL 啟動時不載入權限表,任意用戶無密碼可登錄。
# 登錄 mysql 命令行(無需密碼)
/usr/local/mysql/bin/mysql -u root mysql
# 修改 root 密碼(MySQL 5.7+ authentication_string 字段)
UPDATE user SET authentication_string=PASSWORD('new_password') WHERE user='root';
FLUSH PRIVILEGES;
EXIT;
版本差異:
UPDATE user SET password=PASSWORD('newpwd') WHERE user='root';authentication_string 字段存儲加密密碼。mysql.global_priv 表,建議用 SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpwd');。# 關閉跳過權限的實例 killall mysqld # 或 pkill -9 mysqld # 啟動正常服務 /etc/init.d/mysql start # 或 systemctl start mysqld
mysql -u root -p'new_password' -e "SELECT VERSION();"
mysql_secure_installation:移除匿名用戶、禁止 root 遠程登錄、刪除 test 庫、重新加載權限。validate_password 插件強制長度、大小寫、數字、特殊字符。skip-grant-tables 參數,防止未授權訪問。Windows 下需編輯 my.ini 在 [mysqld] 區段添加 skip-grant-tables,重啟服務,修改密碼後移除該行再重啟。詳見《Navicat for MySQL 1045 錯誤如何解決 (Windows 版)》。
Linux 下重置 MySQL root 密碼核心流程:停服務 → skip-grant-tables 啟動 → 進 mysql 庫更新 authentication_string → FLUSH PRIVILEGES → 重啟正常服務。操作需謹慎,修改完成後務必移除臨時參數,恢復權限保護。