44

mysql忘记密码,该怎么办?

 4 years ago
source link: https://www.tuicool.com/articles/feeQJvB
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文主要介绍,mysql5.7版本的数据库,忘记密码的解决方案!

一、问题背景

很久之前,小编在linux(centos7)服务器上安装了mysql5.7的数据库,但是很长时间没有使用过,也不知道里面是否有有用的数据库,密码也忘记了。

此时,就想是否有一种办法,能找回密码或者修改密码的方案。

于是,就在网上找了一些方案,大体用的最多的就是 skip-grant-tables 解法。

二、解法详解

本例的操作系统是centos7,mysql是5.7的版本,可能不同版本的命令稍有不同,网友可以自行根据系统版本查询相关命令。

2.1、skip-grant-tables模式启动

skip-grant-tables表示,在启动mysql时不启动授权表功能,可以直接免密码登录

#修改/etc/my.cnf文件
vim /etc/my.cnf

#在[mysqld]区域添加配置,并保存my.cnf文件
skip-grant-tables

#重启mysql
systemctl restart mysqld

#登录mysql
mysql -u root -p

#如果出现输入密码,直接回车,就可以进入数据库了

2.2、修改root密码

#登录mysql,此时还没有进入数据库,使用如下命令
use mysql;

#修改root密码(mysql5.7版本)
update user set authentication_string = password('密码'), password_expired = 'N',password_last_changed = now() where user = 'root';

#如果你的mysql是5.6版本修改root密码(mysql5.6版本)
update user set password=password('密码') where user='root';

#使其生效
flush privileges;

#退出
exit;

2.3、新增管理员用户

如果你不想修改root密码,可以新增一个管理员用户,操作如下:

#登录mysql,此时还没有进入数据库,使用如下命令
use mysql;

#刷新数据库
flush privileges;

#创建一个用户,并赋予管理员权限
grant all privileges on *.* to '用户'@'%' identified by '密码';

#例如,创建一个admin用户,密码为admin
grant all privileges on *.* to 'admin'@'%' identified by 'admin';

2.4、重启服务器

上面操作完成之后,其实还没有完,需要关闭授权表功能,重启服务器

#修改/etc/my.cnf文件
vim /etc/my.cnf

#在[mysqld]区域删除改配置,并保存my.cnf文件
#skip-grant-tables

#重启mysql
systemctl restart mysqld

#此时,修改完毕

三、测试连接

使用我们刚刚新建的admin用户进行测试登录

#admin登录
mysql -u admin -p

#输入密码admin,此时可以登录

eYryYnY.jpg!web

四、总结

如果您也出现忘记密码的情况,可以使用此方法解决当前问题。

mysql5.7.6版本后,废弃user表中password()方法,所以旧方法重置密码对mysql8.0版本是行不通的!

mysql8可以采用此方法修改root密码:

#在skip-grant-tables模式下,将root密码置空
update user set authentication_string = '' where user = 'root';

#退出,将/etc/my.cnf文件下的skip-grant-tables去掉,重启服务器
#登录mysql
mysql -u root -p

#因为密码置空,直接回车,进入数据库之后,修改密码
ALTER USER 'root'@'localhost' IDENTIFIED BY 'Hello@123456';

#因为mysql8,使用强校验,所以,如果密码过于简单,会报错,密码尽量搞复杂些!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK