在Linux(CentOS7)下安装MySQL5.x
MySQL是一款数据库,用于存储数据。
1、先使用wget下载mysql安装包
1 | wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz |
2、创建组、用户
后面mysql就使用这个用户来运行(注意这也是mysql启动脚本中默认的用户,因此最好不要改名)。
1 | groupadd mysql |
3、安装
3.1 解压
将前面得到的mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz 解压、解归档
1 | gunzip mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz |
将解压后的目录移动至 /usr/local ,并重命名为 mysql
1 | mv mysql-5.7.22-linux-glibc2.12-x86_64 /usr/local/mysql |
此后 /usr/local/mysql 就是安装目录了
注意,如果mysql目录下没有data和tmp目录,手动新建,并修改权限
3.2 目录权限设置
将mysql及其下所有的目录所有者和组均设为mysql
1 | cd /usr/local/mysql |
3.3 初始化
1 | /usr/local/mysql/bin/mysqld --initialize --user=mysql --datadir=/usr/local/mysql/data --basedir=/usr/local/mysql |
初始化成功后出现如下信息:
201x-xx-xxT07:10:13.583130Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use –explicit_defaults_for_timestamp server option (see documentation for more details).
201x-xx-xx T07:10:13.976219Z 0 [Warning] InnoDB: New log files created, LSN=45790
201x-xx-xx T07:10:14.085666Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
201x-xx-xx T07:10:14.161899Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 1fa941f9-effd-11e5-b67d-000c2958cdc8.
201x-xx-xx T07:10:14.165534Z 0 [Warning] Gtid table is not ready to be used. Table ‘mysql.gtid_executed’ cannot be opened.
201x-xx-xx T07:10:14.168555Z 1 [Note] A temporary password is generated for root@localhost: xxxxxxxxx.
注意最后一行,它给了root一个初始密码(xxxxxxxxx),后面要登录的时候要用到这个密码。
3.4 配置
配置 /etc 下的 my.cnf 文件,如果没有请创建
1 | [mysqld] |
4、后台运行服务端
注意:请将{mysql} 替换成 您的mysql安装路径
1 | {mysql}/bin/mysqld_safe & |
使用ps -ef | grep mysql
或者 netstat -nap | grep 3306
- 查看进程
1 | {mysql}/bin/mysqladmin -uroot -p - 停止 |
如果出现错误,请检查前面几步是否出错。
5、设置mysql以服务运行并且开机启动
将{mysql}/ support-files/mysql.server 拷贝为/etc/init.d/mysql并设置运行权限
1 | cp mysql.server /etc/init.d/mysql |
把mysql注册为开机启动的服务
1 | chkconfig --add mysql |
当然也可以手动进行服务的开启和关闭:
1 | /etc/init.d/mysql start |
6、连接客户端
创建客户端的软链接
1 | ln -s {mysql}/bin/mysql /usr/local/bin/mysql |
客户端连接
1 | mysql -u root -p |
输入刚才的初始化密码进入
进入之后,修改密码
1 | mysql> alter user 'root'@'localhost' identified by '您的新密码'; |
配置远程可以连接
1 | use mysql # 打开mysql数据库 |
关闭远程连接,恢复mysql的默认设置(只能本地连接)
1 | update user set host='localhost' where user='root'; #将host设置为localhost表示只能本地连接mysql |
也可以添加一个用户名为aaa,密码为xxx,权限为%(表示任意ip都能连接)的远程连接用户
1 | grant all on *.* to 'aaa'@'%' identified by 'xxx'; |
至此,MySQL5.7安装完毕。
当然也可以使用Mariadb,它是MySQL5.x的一个分支,命令用法和MySQL5.x是一样的,安装(可以使用yum安装)步骤如下:
1、在安装之前可以先搜索yum管理工具中有没有mariadb的软件包,在命令行下:
yum search mariadb-server mariadb
2、如果存在,就可以使用yum管理工具来安装,在命令行下:
yum install mariadb-server mariadb
等待安装完成
4、启动/停止/重启数据库服务
systemctl start/stop/restart mariadb
设置开机自启
systemctl enable mariadb
取消开机自启
systemctl disable mariadb
4、连接数据库
mysql -u root -p