MySQL忘记root密码解决方法

现在我们使用的mysql数据库分为两个版本了,一个是mysql ,一个是mariadb,两个版本的解决方案有些不同,我会在下面给与说明。

第一步

首先,我们需要打开my.cnf

vim /etc/my.cnf

[mysqld]下添加skip-grant-tables,然后保存并退出

假如没有my.cnf这个文件的话,我们可以在 /etc/mysql/mysql.conf.d/mysqld.cnf[mysqld]下添加skip-grant-tables,然后保存并退出

重启mysql服务器

systemctl restart mysql(mariadb)
或者
service mysql(mariadb) restart

第二步

此时,我们登录进入mysql的时候是不需要输入密码的,但是我们可以修改root密码,我们登录进去后,进入mysql库

[root@ub1 ~]$ mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.21-0ubuntu0.16.04.1 (Ubuntu)
... ...
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> 

修改密码:

UPDATE user SET password=PASSWORD('your_new_passwd')WHERE User='root' ;

但是在mysql上没有password这个字段,但是有一个叫做authentication_string :

mysql> SELECT User,Host,Password FROM user;
ERROR 1054 (42S22): Unknown column 'Password' in 'field list'
mysql> SELECT User,Host,authentication_string FROM mysql.user;
+------------------+-----------+-------------------------------------------+
| User             | Host      | authentication_string                     |
+------------------+-----------+-------------------------------------------+
| root             | localhost | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
| mysql.session    | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys        | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| debian-sys-maint | localhost | *91A4592A144CD258480130DC9002C5D61E82238D |
+------------------+-----------+-------------------------------------------+
4 rows in set (0.01 sec)

所以我们在修改密码的时候将password字段改成authentication_string

mysql> UPDATE user SET authentication_string=PASSWORD('root')WHERE User='root';
Query OK, 0 rows affected, 1 warning (0.31 sec)
Rows matched: 1  Changed: 0  Warnings: 1

刷新:

mysql> flush privileges;

第三步

/etc/my.cnf中的skip-grant-tables注释掉(/etc/mysql/mysql.conf.d/mysqld.cnf)

重启:

systemctl restart mysql(mariadb)
或者
service mysql(mariadb) restart

你可能感兴趣的:(数据库相关)