centos7 yum安装mysql5.7并在root密码忘记的情况下重设密码

时间:2022-05-24 17:27:02

CentOS7的yum源中默认好像是没有mysql的。为了解决这个问题,我们要先下载mysql的repo源。

1. 下载mysql的repo源

1
$ wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm

2. 安装mysql-community-release-el7-5.noarch.rpm包

1
$ sudo rpm -ivh mysql-community-release-el7-5.noarch.rpm

安装这个包后,会获得两个mysql的yum repo源:/etc/yum.repos.d/mysql-community.repo,/etc/yum.repos.d/mysql-community-source.repo。

3. 安装mysql

1
$ sudo yum install mysql-server

根据步骤安装就可以了,不过安装完成后,没有密码,需要重置密码。

4. 重置密码

修改MySQL的登录设置: 
# vim /etc/my.cnf
在[mysqld]的段中加上一句:skip-grant-tables
例如:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
skip-grant-tables
保存并且退出vi。

重新启动mysqld 
# service mysqld restart
Stopping MySQL: [ OK ]
Starting MySQL: [ OK ]

登录并修改MySQL的root密码 
# mysql
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

将MySQL的登录设置修改回来 
# vim /etc/my.cnf
将刚才在[mysqld]的段中加上的skip-grant-tables删除
保存并且退出vim

重新启动mysqld 
# service mysqld restart
Stopping MySQL: [ OK ]
Starting MySQL: [ OK ]

方式二:

# step1:卸载

[root@codecycle ~]# rpm -qa | grep mysql

mysql-5.1.73-3.el6_5.x86_64

mysql-libs-5.1.73-3.el6_5.x86_64

mysql-server-5.1.73-3.el6_5.x86_64

[root@codecycle ~]# rpm -e --nodeps mysql-5.1.73-3.el6_5.x86_64 mysql-libs-5.1.73-3.el6_5.x86_64 mysql-server-5.1.73-3.el6_5.x86_64

# step2: 下载yum包,导入本地

[root@codecycle ~]# yum localinstall /usr/local/src/mysql-community-release-el6-5.noarch.rpm

# step3:安装

[root@codecycle ~]# yum install mysql-community-server

# step4:启动

[root@codecycle ~]# service mysqld start

# step5:开机启动

[root@codecycle ~]# chkconfig --list | grep mysqld

mysqld 0:off 1:off 2:off 3:off 4:off 5:off 6:off

[root@codecycle ~]# chkconfig mysqld on

# step6:设置本地登录密码

[root@codecycle ~]# mysqladmin -uroot -p password 123456

# step7:设置远程登录密码

[root@codecycle ~]# mysql -uroot -p123456

mysql> grant all privileges on *.* to root@'%' identified by 'qaz123wsx' with grant option;

mysql> flush privileges;