下载MySQL安装包,解压后移动至/usr/local/mysql并赋予权限,完成依赖安装、配置和启动。
CentOS7下安装MySQL教程
一、卸载内置环境
1、检查并卸载MariaDB:
rpm -qa | grep mariadb sudo yum remove mariadb-libs mariadb-devel mariadb-server mariadb-client
2、检查并卸载MySQL:
rpm -qa | grep mysql sudo yum remove mysql-community-common mysql-community-libs mysql-community-server mysql-community-client mysql-community-manual
二、下载与配置MySQL Yum源
1、下载MySQL Yum包:
wget http://repo.mysql.com/mysql57-community-release-el7-10.noarch.rpm
2、安装MySQL Yum源:
sudo rpm -Uvh mysql57-community-release-el7-10.noarch.rpm
三、安装MySQL服务端
1、安装MySQL服务端:
sudo yum install -y mysql-community-server
2、启动MySQL服务:
sudo systemctl start mysqld.service
3、查看MySQL服务状态:
sudo systemctl status mysqld.service
四、获取临时密码并修改root用户密码
1、获取临时密码:
grep 'temporary password' /var/log/mysqld.log
2、登录MySQL并修改密码:
mysql -uroot -p ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword!'; FLUSH PRIVILEGES; EXIT;
3、设置全局密码策略(可选):
SET GLOBAL validate_password_policy=0; SET GLOBAL validate_password_length=1;
五、配置MySQL字符集与权限
1、编辑my.cnf配置文件:
vim /etc/my.cnf
添加或修改以下内容:
[mysqld] character-set-server=utf8mb4 collation-server=utf8mb4_general_ci
2、重启MySQL服务:
sudo systemctl restart mysqld.service
3、授权远程访问:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'NewPassword!' WITH GRANT OPTION; FLUSH PRIVILEGES;
六、防火墙配置与自启动设置
1、开放3306端口:
sudo firewall-cmd --zone=public --add-port=3306/tcp --permanent sudo firewall-cmd --reload
2、设置MySQL开机自启动:
sudo systemctl enable mysqld.service
常见问题解答(FAQs)
Q1: 如何检查MySQL是否成功安装?
A1: 你可以通过以下命令来检查MySQL服务的状态:
sudo systemctl status mysqld.service
如果看到“active (running)”则表示MySQL已成功安装并正在运行。
Q2: 如果忘记MySQL root密码怎么办?
A2: 你可以通过跳过授权表的方式重置root密码,具体步骤如下:
1、停止MySQL服务:
sudo systemctl stop mysqld.service
2、以安全模式启动MySQL:
sudo mysqld_safe --skip-grant-tables &
3、登录MySQL:
mysql -uroot
4、修改root密码:
FLUSH PRIVILEGES; ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword!';
5、退出并重启MySQL服务:
EXIT; sudo systemctl restart mysqld.service