TrumanWong

MySQL8忘记密码如何重置密码

TrumanWong
5/14/2023

操作系统:AlmaLinux 9.2

MySQL版本:mysql-server-8.0.32-1.el9_2.x86_64

  1. 首先停止MySQL

    $ systemctl stop mysqld
    
  2. 打开/etc/my.cnf,加入skip_grant_tables

    [mysqld]
    skip_grant_tables
    
  3. 重新启动MySQL

    $ systemctl start mysqld
    
  4. 在命令行内直接输入mysql,执行如下操作:

    mysql> update mysql.user set authentication_string = '' where user = 'root';
    Query OK, 0 rows affected (0.00 sec)
    Rows matched: 1  Changed: 0  Warnings: 0
    
    mysql> delete from mysql.user where user='root' and host='localhost';
    Query OK, 1 row affected (0.00 sec)
    
    mysql> flush privileges;
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> create user 'root' identified by 'password';
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> grant all privileges on *.* to 'root'@'%' with grant option;
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)
    
  5. 再次修改/etc/my.cnf文件,将skip_grant_tables删掉,重启mysqld,即可以重置后的新密码成功登入。