วิธี Reset Root Password ขึ้นอยู่กับ MySQL Version และ OS นี่คือวิธีมาตรฐานสำหรับ MySQL 5.7.6+ / 8.0+
วิธีที่ 1: ALTER USER (MySQL 5.7.6+ / 8.0+) - แนะนำ
-- เข้า MySQL ด้วย Root (ถ้ารู้ Password เดิม)
mysql -u root -p
-- เปลี่ยน Password
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_strong_password';
ALTER USER 'root'@'%' IDENTIFIED BY 'new_strong_password';
FLUSH PRIVILEGES;
วิธีที่ 2: Skip Grant Tables (ลืม Password เดิม)
Step 1: หยุด MySQL Service
# Linux (systemd)
sudo systemctl stop mysqld
# Windows (Admin CMD)
net stop mysql80
Step 2: Start MySQL แบบ Skip Grant Tables
# Linux
sudo mysqld_safe --skip-grant-tables --skip-networking &
# Windows
mysqld --skip-grant-tables --skip-networking
Step 3: เข้า MySQL ไม่ต้อง Password
mysql -u root
Step 4: Reset Password
USE mysql;
-- MySQL 8.0+
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_strong_password';
ALTER USER 'root'@'%' IDENTIFIED BY 'new_strong_password';
-- MySQL 5.7 (Legacy)
UPDATE user SET authentication_string = PASSWORD('new_pass') WHERE User = 'root';
FLUSH PRIVILEGES;
Step 4: Restart MySQL ปกติ
# Linux
sudo systemctl restart mysqld
# Windows
net stop mysql80 && net start mysql80
วิธีที่ 3: mysqladmin (Command Line)
# รู้ Password เดิม
mysqladmin -u root -p'old_pass' password 'new_pass'
# หรือ
mysqladmin -u root -p password 'new_pass'
-- จะถาม Password เดิม
การตรวจสอบ
# ทดสอบ Login ใหม่
mysql -u root -p'new_strong_password' -e "SELECT USER();"
# ดู Users
SELECT User, Host, plugin FROM mysql.user WHERE User = 'root';
⚠️ Security Best Practices
- ใช้ Password แข็งแกร่ง (12+ chars, Mixed case, Numbers, Symbols)
- ห้ามใช้ Root สำหรับ Application
- สร้าง User แยกสำหรับแต่ละ App พร้อมสิทธิ์จำกัด
- เปิด
validate_passwordPlugin - Rotate Password เป็นระยะ
- ใช้ Authentication Plugin:
caching_sha2_password(Default 8.0+)
MySQL 8.0+ Authentication Plugin
-- ดู Plugin ปัจจุบัน
SELECT User, Host, plugin FROM mysql.user;
-- เปลี่ยนเป็น mysql_native_password (ถ้าต้องการ Relative Compatibility)
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';