MySQL之——忘记root账户密码的解决方案

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/l1028386804/article/details/101545517

MySQL 5.7以下版本

1.修改MySQL的登录设置

# vim /etc/my.cnf

在[mysqld]的段中加上一句:skip-grant-tables
例如:

# vim /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
skip-grant-tables

保存并且退出vim。

2.重新启动mysqld

# service mysqld restart
Stopping MySQL: [ OK ]
Starting MySQL: [ OK ]

3.登录并修改MySQL的root密码

# mysql -uroot -p
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 3.23.56
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> USE mysql ;
Database changed
mysql> UPDATE user SET password = password ( 'new-password' ) WHERE User = 'root' ;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 2 Changed: 0 Warnings: 0
mysql> flush privileges ;
Query OK, 0 rows affected (0.01 sec)
mysql> quit

4.将MySQL的登录设置修改回来

# vim /etc/my.cnf

将刚才在[mysqld]的段中加上的skip-grant-tables删除
保存并且退出vim

5.重新启动mysqld

# service mysqld restart
Stopping MySQL: [ OK ]
Starting MySQL: [ OK ]

MySQL 5.7 版本

1.修改 /etc/my.cnf

在 [mysqld] 小节下添加一行:skip-grant-tables=1,这一行配置让 mysqld 启动时不对密码进行验证

vim /etc/my.cnf
[mysqld]
kip-grant-tables=1

2.重启 mysqld 服务

service mysqld restart
或者
systemctl restart mysqld

3.使用 root 用户登录到 MySQL

mysql -u root 

4.切换到mysql数据库,更新 user 表

use mysql;
update user set authentication_string = password('root'), password_expired = 'N', password_last_changed = now() where user = 'root';

在之前的版本中,密码字段的字段名是 password,5.7版本改为了 authentication_string

5.退出 mysql,编辑 /etc/my.cnf 文件,删除 skip-grant-tables=1 的内容
6.重启 mysqld 服务,再用新密码登录即可

注意:

MySQL 5.7 在初始安装后会生成随机初始密码,并在 /var/log/mysqld.log 中有记录,可以通过 cat 命令查看,找 password 关键字找到密码后,在本机以初始密码登录,并且(也只能)通过 alter user 'root'@'localhost' identified by 'root' 命令,修改 root 用户的密码为 root,然后退出,重新以root用户和刚设置的密码进行登录即可。

猜你喜欢

转载自blog.csdn.net/l1028386804/article/details/101545517