mysql忘记root密码

参考

https://blog.csdn.net/wwwer52022222/article/details/66472480

https://blog.csdn.net/jolly10/article/details/79640934

前言

mysql的root密码必须要记着,不然,忘记后,所有的操作都没办法进行。一般情况我们不会忘记root密码,但是有一种情况,就是安装宝塔套件,mysql的root密码是随机的,我们也不知道。我碰到的问题就是需要从binlog还原数据,通过宝塔修改root也不成功,只能通过mysql提供的接口进行。前提是你要登录到mysql安装的服务器上。

添加参数

打开mysql的配置文件

windows在c盘programdata的mysql目录下,名称是my.ini

linux有好几个配置文件的地方,可以修改/etc/mysql/mysql.conf.d/mysqld.cnf

或是在宝塔安装目录下

找到[mysqld]的地方,在[mysqld]下面添加一行skip-grant-tables

重启服务

windows下可以打开cmd,然后运行net stop mysql,再运行net start mysql

linux下运行service mysql restart

或是重启系统

修改root密码

  1. mysql -uroot -p (直接点击回车,密码为空)
  2. use mysql;
  3. 5.7版本及以上运行
  4. update user set authentication_string=password('123456') where user='root';
  5. 5.7版本以下运行
  6. update user set password=password('123456') where user='root';
  7. flush privileges;
  8. exit;

删除参数

删除上面添加的参数skip-grant-tables

重启数据库服务

windows下可以打开cmd,然后运行net stop mysql,再运行net start mysql

linux下运行service mysql restart

或是重启系统

可能的操作

在配置文件中删除skip-grant-tables后,第一次登入数据库会提示你更改密码,否则其它的命令都不会执行

[root@qht131 mysql]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 7
Server version: 5.7.21-log
 
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
 
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
 
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
 
mysql> use mysql
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
 
mysql> set PASSWORD=PASSWORD('123456');
Query OK, 0 rows affected, 1 warning (0.00 sec)

遇到的问题

按照上面的操作完成后,发现还是无法访问,提示1142 select command denied to user admin@::1 for table user

这是因为root只打开了local host的权限,::1是ipv6下的127.0.0.1,所以无法访问,可以在上面删除参数重启数据库服务之前,用navicat或是使用sql语句,修改root权限为%,也就是所有ip都可用。然后再删除参数,重启数据库服务就好了

原文地址:https://www.cnblogs.com/studywithallofyou/p/12250809.html