MySQL忘记root密码的解决办法

使用MySQL时,如果忘记了其他用户的密码,可以使用root用户重新设置,但是如果忘记了root的密码,就要采用特殊的方法进行操作。
直接修改授权表可以修改root的密码,下面详细介绍步骤,以mysql5.7为例。

  1. 停止mysqld服务进程
    [root@localhost ~]# systemctl stop mysqld.service 
    [root@localhost ~]# netstat -ntpln | grep 3306  //检测mysql是否已经启动
  2. 使用mysqld结合skip-grant-tables启动数据库,它的作用是用户登录时不使用授权表,所以用户可以不使用密码直接登录。
    [root@localhost ~]# mysqld --skip-grant-tables&
    [root@localhost ~]# netstat -ntpul | grep 3306  //检测mysql是否已经启动
    tcp6       0      0 :::3306                 :::*                    LISTEN      1561/mysqld 
  3. 可以不使用密码直接登录到mysql,使用update修改root密码。
[root@localhost ~]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.17 Source distribution

mysql> update mysql.user set authentication_string=password('123abc') where user='root'; //修改root密码为123abc
Query OK, 1 row affected, 1 warning (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 1

4.刷新数据库,使用update修改密码后,只是在数据库中进行了修改,内存中的数据并没有修改。flush privileges 的作用就是把当前user和privilege表中的用户信息和权限设置从mysql库提取到内存里。mysql用户数据和权限修改后,希望在不重启mysql服务的情况下直接生效,就需要执行以下命令。

mysql> flush privileges;      //刷新数据库
Query OK, 0 rows affected (0.01 sec)

5.使用新密码做登录测试,登录成功说明修改成功。

[root@localhost ~]# mysql -uroot -p123abc   //登录mysql
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.17 Source distribution

这里注意登录时-p后面直接跟上登录密码,不能有空格,否则就会有错误。

猜你喜欢

转载自blog.51cto.com/11134648/2140411