MySQL 忘记 root 密码的处理办法

1.  编辑/etc/my.cnf 文件

1) 在[mysqld] 下添加以下内容:

skip-grant-tables

2) 重启MySQL 服务

# service mysqld restart

Shutting down MySQL.. SUCCESS!

Starting MySQL. SUCCESS!

2.  直接进入mysql

# mysql

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 2

Server version: 5.7.25 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, 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>

3.  修改回密码

1)  查看密码

mysql> select user,host,authentication_string from mysql.user;

+---------------+-----------+-------------------------------------------+

| user           | host         | authentication_string                      |

+---------------+-----------+-------------------------------------------+

| root           | localhost | *8232A1298A49F710DBEE0B330C42EEC825D4190A |

| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |

| mysql.sys       | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |

+---------------+-----------+-------------------------------------------+

3 rows in set (0.00 sec)

2)  修改密码

情况一:mysql 5.7.6 or later 版本

mysql> update mysql.user set authentication_string=password('P@ssw0rd')   where user='root';

情况二:mysql 5.7.5 or earlier 版本

mysql> update mysql.user set password=password("P@ssw0rd") where user="root" and host="localhost";

4.  修改配置文件,重启MySQL

1)  修改my.cnf 文件

删除或注释skip-grant-tables

2)  重启mysql

# service mysqld restart

Shutting down MySQL.. SUCCESS!

Starting MySQL. SUCCESS!

3)  新密码验证

# mysql -uroot -p'P@ssw0rd'

 

---- end ----