首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

忘記 MySQL root 密碼完整解決方案(Linux/Windows 通用)

     編輯:MySQL 資料庫相關知識

核心原理

跳過權限表啟動 → 免密登入 → 修改 user 表 → 刷新權限 → 正常重啟。

步驟詳解

1. 停止 MySQL 服務

# Linux
kill `cat /var/lib/mysql/hostname.pid`
# 或
systemctl stop mysqld

# Windows
net stop mysql
# 或任務管理器結束 mysqld.exe

PID 文件位置:datadir/hostname.pid

PID 文件

PID 文件內容

2. 跳過權限表啟動

# Linux
mysqld_safe --skip-grant-tables &

# Windows
mysqld --skip-grant-tables

跳過權限啟動

3. 免密登入並修改密碼

mysql
USE mysql;

-- MySQL 5.7+ 欄位名 authentication_string
UPDATE user SET authentication_string = PASSWORD('new_password') WHERE User = 'root';

-- 5.6 及以下
-- UPDATE user SET password = PASSWORD('new_password') WHERE User = 'root';

FLUSH PRIVILEGES;

UPDATE user 表

FLUSH PRIVILEGES

關鍵點: --skip-grant-tables 下 SET PASSWORD 失效,必須直接 UPDATE user 表。

4. 正常重啟驗證

# 關閉 --skip-grant-tables 進程
# 正常啟動
systemctl start mysqld
# 或
net start mysql

# 驗證
mysql -u root -p'new_password'

驗證登入

Windows 圖形化替代方案

  1. 服務管理器停止 MySQL
  2. 註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MySQL\ImagePath 末尾添加 --skip-grant-tables
  3. 啟動服務 → 免密登入修改 → 移除參數 → 重啟

預防建議

  • 使用密碼管理器存儲 root 密碼
  • 建立專用運維帳號,降低 root 使用頻率
  • 配置 validate_password 插件強制強密碼策略
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved