修改當前登入用戶密碼
-- 方式 1:SET PASSWORD(推薦 5.7+)
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpwd');
-- 方式 2:UPDATE user 表
UPDATE mysql.user SET authentication_string=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;
管理員重置其他用戶密碼
-- 方式 1
SET PASSWORD FOR 'user'@'host' = PASSWORD('newpwd');
-- 方式 2
UPDATE mysql.user SET authentication_string=PASSWORD('newpwd') WHERE User='user' AND Host='host';
FLUSH PRIVILEGES;
命令列工具 mysqladmin(外部命令)
# 首次設定 root 密碼
mysqladmin -u root password 'newpwd'
# 已有密碼時修改
mysqladmin -u root -p'oldpwd' password 'newpwd'
# 指定主機
mysqladmin -u root -h host_name password 'newpwd'
Linux 安裝後初始化密碼
# 方法 1:mysqladmin(最簡單)
mysqladmin -u root password 'newpwd'
# 方法 2:SET PASSWORD
mysql -u root
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpwd');
SET PASSWORD FOR 'root'@'host_name' = PASSWORD('newpwd');
# 方法 3:UPDATE user 表
mysql -u root
UPDATE mysql.user SET Password = PASSWORD('newpwd') WHERE User = 'root';
FLUSH PRIVILEGES;
忘記 Root 密碼:緊急重置
- 停止 MySQL:
systemctl stop mysqld / net stop mysql
- 跳過權限啟動:
mysqld_safe --skip-grant-tables & / mysqld --skip-grant-tables
- 免密登入:
mysql -u root
- 重置密碼:
UPDATE mysql.user SET authentication_string=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;
- 正常重啟 MySQL
終極一鍵命令
mysqladmin -u root -p"old_password" password "new_password"
MySQL 8.0+ 重要變更
PASSWORD() 函數已移除
- 統一使用
ALTER USER:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpwd';
authentication_string 欄位存儲加密密碼
caching_sha2_password 為預設驗證插件
避坑提醒
- 密碼含特殊字元(@#$% 等)請用單引號包裹
FLUSH PRIVILEGES 必須執行,否則修改不生效
- 修改 root 密碼後,檢查應用配置檔、備份腳本、監控腳本同步更新