首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

Windows/MySQL 1045 錯誤(Access denied for root)完整重置密碼指南:官方 init-file 法、跳過授權表法、debian.cnf 法三大方案

     編輯:MySQL 綜合教學

錯誤 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) 通常因密碼遺忘、權限表損壞、Host 不匹配導致。本文提供 Windows 官方 --init-file 法、通用 --skip-grant-tables 法、Debian/Ubuntu 專用 debian.cnf 法三大方案,覆蓋 99% 場景。

方案一:Windows 官方 --init-file 法(推薦生產環境)

  1. 以管理員身份登錄,停止 MySQL 服務(服務管理器或任務管理器殺進程)。
  2. 創建文本文件 C:\mysql-init.txt,單行寫入:
    SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPassword');
  3. 命令行啟動 MySQL 讀取初始化文件:
    C:\mysql\bin\mysqld-nt --init-file=C:\mysql-init.txt
  4. 服務啟動後密碼已重置,刪除 mysql-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/Ubuntu 專用 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

優勢:無需停機、無需跳過授權、不影響業務連接。

Windows 圖形化替代: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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved