Hướng dẫn ngắn gọn chi tiết reset mật khẩu root MySQL bị quên/mất trên Windows hoặc Linux.
Background
Bạn từng quên mật khẩu root MySQL? Việc này xảy ra dù có nhiều phòng ngừa. Kết quả: bị khóa khỏi database server. Không tạo database mới, kiểm soát server bị hạn chế. Biết cách lấy lại root access rất hữu ích. Đây là cách reset password user root trong MySQL trên Windows và Linux.
Reset MySQL Root Password trên Windows
Đăng nhập server sebagai Administrator. Kill MySQL server nếu đang chạy. Dùng Windows Services Manager: Start Menu → Control Panel → Administrative Tools → Services. Tìm MySQL server và stop. Nếu không có trong list mà MySQL vẫn chạy → không chạy as service. Mở Task Manager (Ctrl+Alt+Del), kill process MySQL.
Với MySQL đã stop, buộc đổi password bằng kết hợp UPDATE và FLUSH. Mở text editor, tạo file mới, nhập nội dung sau (thay "NewMySQLPassword" bằng password mới):
UPDATE mysql.user SET Password=PASSWORD("NewMySQLPassword") WHERE User='root'; FLUSH PRIVILEGES;
Dòng 1: update field "Password" trong table mysql.user cho user "root" thành "NewMySQLPassword". Dòng 2: flush privileges cũ, đảm bảo password mới dùng mọi nơi. Lưu file làm C:\mysql_reset.txt.
Tiếp, start MySQL server với file này làm config parameter. Mở terminal: Start → Run → cmd → Enter. Chạy lệnh:
C:\mysql\bin\mysqld-nt --init-file=C:\mysql_reset.txt
Server start xong, xóa file C:\mysql_reset.txt. Root password đã reset. Khởi động lại MySQL server bình thường (qua Services Manager). Password mới giờ hoạt động.
Reset MySQL Root Password trên Linux
Đăng nhập Linux as root user. Các bước: stop MySQL server, restart без grant tables (bỏ qua permission) để login root không cần password, set password mới, restart bình thường. Cụ thể:
Stop MySQL server:
# /etc/init.d/mysql stop
Start MySQL với option --skip-grant-tables (chạy không load permission):
# mysqld_safe --skip-grant-tables &
Dấu & cuối chạy background. Login MySQL as root:
# mysql -u root
Sẽ vào được không hỏi password. Các bước set password mới:
mysql> use mysql;
mysql> update user set password=PASSWORD("NewMySQLPassword") where User='root';
mysql> flush privileges;
mysql> quit
Thay "NewMySQLPassword" bằng password của bạn. Giải thích: dòng 1 chọn table config MySQL. Dòng 2 update password cho root. Dòng 3 flush privileges. Bước cuối: restart server bình thường và login với password mới:
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
# mysql -u root -pNewMySQLPassword
Chúc mừng, password root MySQL mới đã set, server sẵn sàng dùng lại. Nhớ update tất cả app dùng password này.