【图文教程】MySQL

MySQL

  • 1. MySQL介绍
  • 2. MySQL安装
  • 3. 设置更改 MySQL root 密码
  • 4. 连接MySQL
  • 5. MySQL常用命令
  • 6. MySQL用户管理以及授权
  • 7. 常用SQL语句
  • 8. MySQL数据库备份恢复
  • 9. MariaDB安装
  • 10. MariaDB慢查询日志
  • 11. MySQL扩展

1. MySQL介绍

数据库是与应用程序实现信息交互的数据存储、管理软件,并且存储数据的也都可以称为数据库。

MySQL 数据库:由瑞典 MySQL AB 公司开发,目前属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL 是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件。

MariaDB 数据库管理系统则是 MySQL 的一个分支,主要由开源社区在维护,采用 GPL 授权许可 MariaDB 的目的是完全兼容 MySQL,包括 API 和命令行,使之能轻松成为 MySQL 的代替品。在存储引擎方面,使用 XtraDB 引擎来代替 MySQL 的 InnoDB 引擎。 MariaDB 由 MySQL 的创始人Michael Widenius(英语:Michael Widenius)主导开发,因为他早前曾以 10 亿美元的价格,将自己创建的公司 MySQL AB 卖给了 SUN,此后,随着 SUN 被甲骨文收购,MySQL 的所有权也落入 Oracle 的手中。Oracle 公司收购了 MySQL 后,有将 MySQL 闭源的潜在风险,因此社区采用分支的方式来避开这个风险。 过去一年中,大型互联网用户以及 Linux 发行商纷纷抛弃 MySQL,转投 MariaDB 阵营。MariaDB 是目前最受关注的 MySQL 数据库衍生版,也被视为开源数据库 MySQL 的替代品。MariaDB 虽然被视为 MySQL 数据库的替代品,但它在扩展功能、存储引擎以及一些新的功能改进方面都强过 MySQL 。MariaDB 名称来自 Michael Widenius 的女儿 Maria 的名字。

MariaDB 基于事务的 Maria 存储引擎,替换了 MySQL 的 MyISAM 存储引擎,它使用了 Percona的 XtraDB,InnoDB 的变体,分支的开发者希望提供访问即将到来的 MySQL 5.4 InnoDB 性能。这个版本还包括了 PrimeBase XT (PBXT) 和 FederatedX 存储引擎。

2. MySQL安装

讲义


MySQL的几个常用安装包:rpm、源码、二进制免编译

二进制免编译包是相当于发布之前就在一台 Linux 服务器进行了编译,编译后将文件整合到了一个目录,然后再将这些目录和文件打包压缩后再发布出来。二进制免编译包有一个好处,就是我们不用花费那么多时间去编译,直接拿过来安装就就可以了。

二进制免编译包和 rpm 包有点类似,但是 rpm 包有一个缺点,就是没办法去定义安装路径,因为 rpm 包默认装在 usr 目录下,二进制免编译包则可以自由指定安装路径。

二进制免编译包毕竟是在别的机器上编译的,虽然不会有什么大的问题,但是想追求完美还是自己编译源码包要好一些。

要下载与操作系统相对应位数的二进制免编译包,查看自己操作系统位数的命令是 uname -a,x86_64的就是 64位,i686、i586 之类的则是 32位,如果这个链接失效可以去 r.aminglinux.com上去找。


MySQL二进制免编译安装包:wget http://mirrors.163.com/mysql/Downloads/MySQL-5.6/mysql-5.6.43-linux-glibc2.12-x86_64.tar.gz

1. cd /usr/local/src
2. wget http://mirrors.163.com/mysql/Downloads/MySQL-5.6/mysql-5.6.43-linux-glibc2.12-x86_64.tar.gz
3. tar zxvf mysql-5.6.43-linux-glibc2.12-x86_64.tar.gz
4. mv mysql-5.6.43-linux-glibc2.12-x86_64 /usr/local/mysql
5. cd /usr/local/mysql
6. useradd mysql  
7. mkdir /data/  
8. ./scripts/mysql_install_db --user=mysql --datadir=/data/mysql  

9. cp support-files/my-default.cnf  /etc/my.cnf 
1) 定义datadir和socket

10. cp support-files/mysql.server /etc/init.d/mysqld

11. vi /etc/init.d/mysqld
1) 定义basedir和datadir
2) chkconfig --add mysqld
3) chkconfig --list
4) /etc/init.d/mysqld start或者service mysqld start
  • 规定所有的安装包放在/usr/local/src/目录下
cd /usr/local/src/
  • 下载mysql软件包
wget http://mirrors.163.com/mysql/Downloads/MySQL-5.6/mysql-5.6.45-linux-glibc2.12-x86_64.tar.gz
  • 解压mysql压缩包
tar zxvf mysql-5.6.45-linux-glibc2.12-x86_64.tar.gz
  • 移动文件到/usr/local/下,并且将目录名称改为mysql
mv mysql-5.6.45-linux-glibc2.12-x86_64 /usr/local/mysql
  • 查看/usr/local/mysql/下的文件和目录

在这里插入图片描述

  • 创建mysql用户
useradd mysql
  • 创建/data/存放mysql数据,如果存在/data/就不用创建了
mkdir /data/
  • 初始化即是定义数据库目录
./scripts/mysql_install_db --user=mysql --datadir=/data/mysql  

--user=mysql           #用户是mysql
--datadir=/data/mysql  #数据存放在/data/mysql/
  • 初始化时报错
第一次安装mysql需要先安装:

yum install -y perl-devel
yum install -y perl-Data-Dumper.x86_64
yum install -y libaio* 
  • 继续初始化,并验证是否安装成功
./scripts/mysql_install_db --user=mysql --datadir=/data/mysql  

echo $?
  • 编辑mysql配置文件默认是在/etc/my.cnf
vim /etc/my.cnf

[mysqld]
datadir=/data/mysql              #指定数据存放目录
socket=/tmp/mysql.sock           #指定套接字存放目录
log-error=/data/mysql/error.log  #指定错误日志存放在哪个目录下
key_buffer=16K
table_open_cache=4
query_cache_limit=256K
query_cache_size=4M
max_allowed_packet=1M
sort_buffer_size=64K
read_buffer_size=256K
thread_stack=64K
innodb_buffer_pool_size = 56M

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd

[mysqld_safe]
#log-error=/data/mysql/error.log  #注释掉
#pid-file=/data/mysql/pid.file    #注释掉

#
# include all files from the config directory
#
#!includedir /etc/my.cnf.d        #注释掉
  • 编辑mysql启动脚本
cd support-files/
cp support-files/mysql.server /etc/init.d/mysqld
vim /etc/init.d/mysqld

【图文教程】MySQL_第1张图片

  • 给/etc/init.d/mysqld设置755权限
chmod 755 /etc/init.d/mysqld 
  • 将mysql设置为开机启动
chkconfig --add mysqld     #将mysql添加到开机启动
chkconfig --list           #查看开机启动列表

Note: This output shows SysV services only and does not include native
      systemd services. SysV configuration data might be overridden by native
      systemd configuration.

      If you want to list systemd services use 'systemctl list-unit-files'.
      To see services enabled on particular target use
      'systemctl list-dependencies [target]'.

aegis          	0:off	1:off	2:on	3:on	4:on	5:on	6:off
mysqld         	0:off	1:off	2:on	3:on	4:on	5:on	6:off
netconsole     	0:off	1:off	2:off	3:off	4:off	5:off	6:off
network        	0:off	1:off	2:on	3:on	4:on	5:on	6:off
  • 启动mysqld服务
1. 使用service启动:service mysqld restart
2. 使用mysqld脚本启动:/etc/inint.d/mysqld restart
  • 停止mysql服务
1. 使用 service 启动:service mysqld stop
2. 使用 mysqld 脚本启动:/etc/inint.d/mysqld stop
  • 查看mysql进程

在这里插入图片描述

  • 查看监听端口

【图文教程】MySQL_第2张图片

  • 结束进程

killall 要安全一些,因为使用 kill 会直接中断,killall 可以先让进程把内存中的数据读写完成之后,再杀死这个进程,kill 则不会这么做,所以使用 kill 命令可能会有丢失数据的风险。

所以当你遇到使用 killall 命令杀死进程的时候,发现过了一两分钟进程还存在,不要直接 killall -9 去杀死进程。因为可能你这个进程读写的数据比较多,所以需要一定的时间等待它读写完成,如果直接 killall -9 会丢失数据或者损坏文件。

killall mysqld

3. 设置更改 MySQL root 密码

讲义

1. 更改环境变量PATH,增加mysql绝对路径
2. mysqladmin -uroot password '123456'
3. mysql -uroot -p123456
4. 密码重置
5. vi /etc/my.cnf//增加skip-grant
6. 重启mysql服务 /etc/init.d/mysqld restart
7. mysql -uroot
8. use mysql;
9. update user set password=password('aminglinux') where user='root';

root 是 mysql 的最高权限用户,和Linux的root概念一样。默认情况下,mysql的roo 用户密码是空的,可以直接登录。但是这样不安全,所以要设置密码。

  • 把mysql命令加入环境变量PATH,不然就得使用绝对路径
export PATH=$PATH:/usr/local/mysql/bin/
  • 想要永久生效,需要配置到/etc/profile里
vim /etc/profile

【图文教程】MySQL_第3张图片

  • 重新加载profile文件
source /etc/profile
  • 设置root密码
mysqladmin -uroot password '123'

#下面不是错误是个警告,是提示设置的密码显示在命令行上了
Warning: Using a password on the command line interface can be insecure.  

#下面这样登陆就会报错,显示需要密码登陆
mysql -uroot  
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)  
  • 测试登录
mysql -uroot -p'123'

Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  • 已知原密码,更改新密码

以下这种更改root密码的方式需要知道原本的密码才能进行更改,不然无法更改,也是使用mysqladmin命令进行更改

mysqladmin -uroot -p'123' password 'aminglinux'
#注意:必须知道原来的密码,才能设置新密码
  • 忘记root密码,怎样重置密码,编辑my.cnf配置文件加入以下内容
vim /etc/my.cnf

[mysqld]
skip-grant             #加这一行,意思是忽略授权 高版本输入 skip-grant-tables
datadir=/data/mysql
socket=/tmp/mysql.sock
  • 重启mysql服务
/etc/init.d/mysqld restart
  • mysql -uroot直接登录
mysql -uroot  #不用加-p不需要密码直接登录

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  • 切换到mysql库
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
  • 查看user表的表结构
mysql> desc user;
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                  | Type                              | Null | Key | Default               | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                   | char(60)                          | NO   | PRI |                       |       |
| User                   | char(16)                          | NO   | PRI |                       |       |
| Password               | char(41)                          | NO   |     |                       |       |
| Select_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Reload_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Shutdown_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Process_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| File_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Grant_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| References_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Index_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Show_db_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Super_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tmp_table_priv  | enum('N','Y')                     | NO   |     | N                     |       |
| Lock_tables_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Execute_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_slave_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_client_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Create_view_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Show_view_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Create_routine_priv    | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_routine_priv     | enum('N','Y')                     | NO   |     | N                     |       |
| Create_user_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Event_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Trigger_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tablespace_priv | enum('N','Y')                     | NO   |     | N                     |       |
| ssl_type               | enum('','ANY','X509','SPECIFIED') | NO   |     |                       |       |
| ssl_cipher             | blob                              | NO   |     | NULL                  |       |
| x509_issuer            | blob                              | NO   |     | NULL                  |       |
| x509_subject           | blob                              | NO   |     | NULL                  |       |
| max_questions          | int(11) unsigned                  | NO   |     | 0                     |       |
| max_updates            | int(11) unsigned                  | NO   |     | 0                     |       |
| max_connections        | int(11) unsigned                  | NO   |     | 0                     |       |
| max_user_connections   | int(11) unsigned                  | NO   |     | 0                     |       |
| plugin                 | char(64)                          | YES  |     | mysql_native_password |       |
| authentication_string  | text                              | YES  |     | NULL                  |       |
| password_expired       | enum('N','Y')                     | NO   |     | N                     |       |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
43 rows in set (0.00 sec)
  • 修改Password字段,sql语句如下
mysql> update user set password=password('123') where user='root';  #重置新密码命令
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4  Changed: 4  Warnings: 0

注意:

mysql在5.7.36版本之后把密码字段存到了authentication_string字段里,在之前版本存在password字段里。

5.7版本以后更改密码的sql语句如下:

update user set authentication_string=password("aming-linux") where user='root';

  • 编辑/etc/my.cnf
vim /etc/my.cnf

[mysqld]
skip-grant             #删掉这一行
datadir=/data/mysql
socket=/tmp/mysql.sock
  • 重启 mysql,这时登录就需要使用你更改后的密码了
vim /etc/my.cnf             #编辑配置文件

/etc/init.d/mysqld restart  #重启mysql

mysql -uroot -p'123'        #输入新密码登录

Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  • MariaDB14-15版本 修改默认密码
1、修改 my.ini,在 [mysqld] 小节下添加一行:skip-grant-tables=1

这一行配置让 mysqld 启动时不对密码进行验证

2、重启 mysqld 服务

3、使用 root 用户登录到 mysql:mysql -uroot 

4、切换到mysql数据库 MariaDB [(none)]> use mysql;,更新 user 表:

update user set password = password('12345') where user = 'root';

如果出现 Column 'Password' is not updatable 这个错误,可以用下面的方法修改密码

alter user 'root'@'localhost' identified by '12345';

5. MariaDB [mysql]>flush privileges; 

6、退出 mysql,编辑 my.ini 文件,删除 skip-grant-tables=1 的内容

7、重启 mysqld 服务,用新密码登录测试一下

4. 连接MySQL

【图文教程】MySQL_第4张图片

  • 连接本地的数据库
[root@sc ~]# mysql -uroot -p'123'
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  • 连接远程
[root@sc ~]# mysql -uroot -p'123' -h127.0.0.1 -P3306  # -h指定 host(IP-P指定端口 
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  • 通过 sock 连接,这种情况只适合在本机使用
[root@sc ~]# mysql -uroot -p'123' -S/tmp/mysql.sock  # -S 指定 sock 文件
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  • 执行 mysql 后的 sql 语句(多数使用在 shell 脚本里)
[root@sc ~]# mysql -uroot -p'123' -e "show databases"  #查看都有什么数据库
Warning: Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+

5. MySQL常用命令

【图文教程】MySQL_第5张图片
【图文教程】MySQL_第6张图片

mysql 的命令需要登录进 mysql 才能进行执行,所以在这之前才要介绍如何去连接 mysql,既然知道如何连接 mysql 后就开始使用一下 mysql 的常用命令吧

  • 查询库 show databases;
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)
  • 切换库 use mysql; 这条命令是切换到了 mysql 库下
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
  • 查看库里所有的表 show tables;
mysql> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
28 rows in set (0.00 sec)
  • 查看表里的字段 desc tb_name; 库包含着表,而表包含着字段
mysql> desc user;  #查看 user 表
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                  | Type                              | Null | Key | Default               | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                   | char(60)                          | NO   | PRI |                       |       |
| User                   | char(16)                          | NO   | PRI |                       |       |
| Password               | char(41)                          | NO   |     |                       |       |
| Select_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Reload_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Shutdown_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Process_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| File_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Grant_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| References_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Index_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Show_db_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Super_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tmp_table_priv  | enum('N','Y')                     | NO   |     | N                     |       |
| Lock_tables_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Execute_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_slave_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_client_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Create_view_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Show_view_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Create_routine_priv    | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_routine_priv     | enum('N','Y')                     | NO   |     | N                     |       |
| Create_user_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Event_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Trigger_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tablespace_priv | enum('N','Y')                     | NO   |     | N                     |       |
| ssl_type               | enum('','ANY','X509','SPECIFIED') | NO   |     |                       |       |
| ssl_cipher             | blob                              | NO   |     | NULL                  |       |
| x509_issuer            | blob                              | NO   |     | NULL                  |       |
| x509_subject           | blob                              | NO   |     | NULL                  |       |
| max_questions          | int(11) unsigned                  | NO   |     | 0                     |       |
| max_updates            | int(11) unsigned                  | NO   |     | 0                     |       |
| max_connections        | int(11) unsigned                  | NO   |     | 0                     |       |
| max_user_connections   | int(11) unsigned                  | NO   |     | 0                     |       |
| plugin                 | char(64)                          | YES  |     | mysql_native_password |       |
| authentication_string  | text                              | YES  |     | NULL                  |       |
| password_expired       | enum('N','Y')                     | NO   |     | N                     |       |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
43 rows in set (0.00 sec)

【图文教程】MySQL_第7张图片

  • 查看建表语句 show create table tb_name\G; 如果不加 G 会显示得很乱
mysql> show create table user\G;
*************************** 1. row ***************************
       Table: user
Create Table: CREATE TABLE `user` (
  `Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT '',
  `User` char(16) COLLATE utf8_bin NOT NULL DEFAULT '',
  `Password` char(41) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL DEFAULT '',
  `Select_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Insert_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Update_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Delete_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Drop_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Reload_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Shutdown_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Process_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `File_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Grant_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `References_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Index_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Alter_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Show_db_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Super_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_tmp_table_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Lock_tables_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Execute_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Repl_slave_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Repl_client_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_view_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Show_view_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_routine_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Alter_routine_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_user_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Event_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Trigger_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_tablespace_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `ssl_type` enum('','ANY','X509','SPECIFIED') CHARACTER SET utf8 NOT NULL DEFAULT '',
  `ssl_cipher` blob NOT NULL,
  `x509_issuer` blob NOT NULL,
  `x509_subject` blob NOT NULL,
  `max_questions` int(11) unsigned NOT NULL DEFAULT '0',
  `max_updates` int(11) unsigned NOT NULL DEFAULT '0',
  `max_connections` int(11) unsigned NOT NULL DEFAULT '0',
  `max_user_connections` int(11) unsigned NOT NULL DEFAULT '0',
  `plugin` char(64) COLLATE utf8_bin DEFAULT 'mysql_native_password',
  `authentication_string` text COLLATE utf8_bin,
  `password_expired` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  PRIMARY KEY (`Host`,`User`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Users and global privileges'
1 row in set (0.00 sec)

ERROR: 
No query specified

【图文教程】MySQL_第8张图片

  • 查看当前用户 select user(); 这个 user() 是一个函数:

如果你用的是远程登录,那么这里显示的是root@主机名,本地登录才会显示root@localhost

mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)
  • 在 /root/.mysql_history 文件里记录着 mysql 的命令历史
[root@sc ~]# cat /root/.mysql_history 
_HiStOrY_V2_
ecit
use\040mysql;
desc\040user;
quti
show\040databases;
use\040mysql;
show\040tables;
desc\040tb_name;
desc\040use
desc\040user
desc\040uer
desc\040user;
use\040mysql
desc\040user;
show\040create\040table\040tb_name\134G;
show\040create\040table\040user\134G;
select\040user();
  • 查看当前使用的数据库 select database();
mysql> select database();
+------------+
| database() |
+------------+
| NULL       |
+------------+
1 row in set (0.00 sec)
  • 创建库 create database db1;
mysql> create database db1;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| db1                |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.00 sec)

【图文教程】MySQL_第9张图片

  • 创建表 use db1; create table t1(id int(4), name char(40));
mysql> use db1
Database changed
mysql> create table t1(`id` int(4), `name` char(40));
Query OK, 0 rows affected (0.03 sec)
  • 这时我们使用 show create table t1\G; 语句就可以看到这个表的创建语句,末尾跟的是默认的引擎和默认的字符集
mysql> show create table t1\G;
*************************** 1. row ***************************
       Table: t1
Create Table: CREATE TABLE `t1` (
  `id` int(4) DEFAULT NULL,
  `name` char(40) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1  #引擎=InnoDB 默认字符集=latin1
1 row in set (0.00 sec)

ERROR: 
No query specified

【图文教程】MySQL_第10张图片

  • 如果不想使用这个默认的字符集,可以在创建表的时候指定其他的字符集
mysql> drop table t1;  #删除表的语句
mysql> create table t1(`id` int(4), `name` char(40)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.28 sec)

mysql> show create table t1\G;
*************************** 1. row ***************************
       Table: t1
Create Table: CREATE TABLE `t1` (
  `id` int(4) DEFAULT NULL,
  `name` char(40) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR: 
No query specified

【图文教程】MySQL_第11张图片

  • 查看当前数据库版本 select version();
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.6.43    |
+-----------+
1 row in set (0.00 sec)

mysql>
  • 查看数据库状态 show status;
mysql> show status;

【图文教程】MySQL_第12张图片

  • 查看各参数 show variables; 会列出很多内容
mysql> show variables;

【图文教程】MySQL_第13张图片

  1. 查看具体的参数,例如我要查看 max_connect_errors 参数:
mysql> show variables like 'max_connect_errors';

【图文教程】MySQL_第14张图片

  1. 如果想要查看某个参数,但是不记得完整的名称了,可以使用模糊查询:
mysql> show variables like 'max_connect%';

【图文教程】MySQL_第15张图片

  • 修改参数 set global max_connect_errors=1000;

永久生效需要去 my.cnf 里修改

mysql> set global max_connect_errors=1000;

【图文教程】MySQL_第16张图片

  • 查看队列 show processlist; 查看队列相当于在 Linux 使用 ps 或者 top 命令查看系统状况一样
mysql> show processlist;

【图文教程】MySQL_第17张图片

mysql> show full processlist;  #更完整的查看队列情况

【图文教程】MySQL_第18张图片

6. MySQL用户管理以及授权

【图文教程】MySQL_第19张图片

搭建一个网站时,后台的应用程序会连接 mysql,连接mysql 就需要一个用户密码,但是不能让它使用 root 用户,root 用户的权限太高不安全,所以需要创建一个用户,并授予这个用户一些权限,你可以具体的授予这些用户的某些权限,让它能操作什么不能操作什么。

下面就来介绍一下如何创建mysql用户以及授权:

  • 创建用户,语句如下
all:表示所有权限    
*.*  表示允许操作那些库和表,库和表用.分开  
第一个 * 表示库名 比如 mysql库,db1库,可以写成:db1.*  这就代表 db1库和所有表
第二个 * 表示表名
mysql> grant all on *.* to 'user1'@'127.0.0.1' identified by '123';

【图文教程】MySQL_第20张图片

[root@sc ~]# mysql -uroot -p123
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> grant all on *.* to 'user1'@'127.0.0.1' identified by '123';  #创建用户user1,ip是127.0.0.1
Query OK, 0 rows affected (0.00 sec)

mysql> ^DBye
[root@sc ~]# mysql -uuser1 -p'123' -h127.0.0.1
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

常识:这种 grant 语句是不会记录到命令历史里的,因为不安全。

  • 如果想要创建一个可以本地连接的 mysql 用户,在创建时指定 localhost 就可以了,创建为可以本地连接的用户,登录时就不需要使用-h指定来源IP了
mysql> grant all on *.* to 'user1'@'localhost' identified by '123';
[root@sc ~]# mysql -uroot -p123  #切换到mysql下登录          
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> grant all on *.* to 'user1'@'localhost' identified by '123';  #创建 localhost 
Query OK, 0 rows affected (0.00 sec)

mysql> ^DBye
[root@sc ~]# mysql -uuser1 -p123
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 23
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
  • 使用 show grants; 可以看到当前用户拥有哪些权限
mysql> show grants;
+-----------------------------------------------------------------------------------------------------------------------+
| Grants for user1@localhost                                                                                            |
+-----------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'user1'@'localhost' IDENTIFIED BY PASSWORD '*23AE809DDACAF96AF0FD78ED04B6A265E05AA257' |
+-----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
  • 如果想看具体的某个用户的话,在命令后加上 for 用户名@登录方式 即可,示例:show grants for user1@‘localhost’;
mysql> show grants for user1@'127.0.0.1';
+-----------------------------------------------------------------------------------------------------------------------+
| Grants for user1@127.0.0.1                                                                                            |
+-----------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'user1'@'127.0.0.1' IDENTIFIED BY PASSWORD '*23AE809DDACAF96AF0FD78ED04B6A265E05AA257' |
+-----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>
  • 我们再创建一个用户,给这个用户授予具体对某个库的操作权限
mysql> grant SELECT,UPDATE,INSERT on db1.* to 'user2'@'192.168.85.132' identified by 'passwd';
Query OK, 0 rows affected (0.00 sec)

mysql>

在这里插入图片描述

  • 现在我们查看一下 user2 的权限

可以看到 user2 具体能执行的 sql 语句,和可以操作哪个库的哪些表。

mysql> show grants for user2@'192.168.85.132';
+-------------------------------------------------------------------------------------------------------------------+
| Grants for user2@192.168.85.132                                                                                   |
+-------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'user2'@'192.168.85.132' IDENTIFIED BY PASSWORD '*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0' |
| GRANT SELECT, INSERT, UPDATE ON `db1`.* TO 'user2'@'192.168.85.132'                                               |
+-------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql>

【图文教程】MySQL_第21张图片

  • 当你想增加用户的连接 IP 或者其他权限时,就可以直接复制 show grants 命令显示出来的语句,然后更改 IP 即可,例如我要让 user2 能使用 192.168.85.133 这个IP登录,然后再 show grants 看一下
mysql> GRANT USAGE ON *.* TO 'user2'@'192.168.85.133' IDENTIFIED BY PASSWORD '*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT SELECT, INSERT, UPDATE ON `db1`.* TO 'user2'@'192.168.85.133';
Query OK, 0 rows affected (0.01 sec)

mysql> show grants for user2@'192.168.85.133';
+-------------------------------------------------------------------------------------------------------------------+
| Grants for user2@192.168.85.133                                                                                   |
+-------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'user2'@'192.168.85.133' IDENTIFIED BY PASSWORD '*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0' |
| GRANT SELECT, INSERT, UPDATE ON `db1`.* TO 'user2'@'192.168.85.133'                                               |
+-------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql>

【图文教程】MySQL_第22张图片

【图文教程】MySQL_第23张图片

  • 原本的 IP 也能连接,这个操作是增加一个可以连接的 IP
mysql> show grants for user2@'192.168.85.132';
+-------------------------------------------------------------------------------------------------------------------+
| Grants for user2@192.168.85.132                                                                                   |
+-------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'user2'@'192.168.85.132' IDENTIFIED BY PASSWORD '*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0' |
| GRANT SELECT, INSERT, UPDATE ON `db1`.* TO 'user2'@'192.168.85.132'                                               |
+-------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql>
  • 针对MySQL创建用户后无法登录的原因

mysql> grant all on sc.* to ‘user3’@’%’ identified by ‘123’;

解决网址:https://blog.csdn.net/silyvin/article/details/53351146

[root@sc ~]# mysql -uroot -p123
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 17
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> grant all on sc.* to 'user3'@'%' identified by '123'  #创建语句如下,其中@“%”是可以在任何地址登录
    -> ;
Query OK, 0 rows affected (0.00 sec)

[root@sc ~]# mysql -uuser3 -p123  #使用 user3 登录不上去
Warning: Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'user3'@'localhost' (using password: YES)
[root@sc ~]# mysql -uroot -p123  #切换到 mysql 下
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> grant all on test.* to user3@"localhost" identified by '123';  #创建 user3@localhost 用户
Query OK, 0 rows affected (0.01 sec)

mysql> ^DBye
[root@sc ~]# mysql -uuser3 -p123  #再次用 user3 登录,成功
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 20
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

7. 常用SQL语句

【图文教程】MySQL_第24张图片

  • 查看 mysql 库中的 user 表有多少行,count 是一个统计行数的函数
mysql> select count(*) from mysql.user;
+----------+
| count(*) |
+----------+
|       12 |
+----------+
1 row in set (0.00 sec)

mysql>
  • 查看 mysql 库中的 db 表里的所有内容

mysql.user :表示查询 mysql 库中的 user 表 *表示所有数据

mysql> select * from mysql.db\G;
*************************** 1. row ***************************
                 Host: %
                   Db: test
                 User: 
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: Y
          Create_priv: Y
            Drop_priv: Y
           Grant_priv: N
      References_priv: Y
           Index_priv: Y
           Alter_priv: Y
Create_tmp_table_priv: Y
     Lock_tables_priv: Y
     Create_view_priv: Y
       Show_view_priv: Y
  Create_routine_priv: Y
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: Y
         Trigger_priv: Y
*************************** 2. row ***************************
                 Host: %
                   Db: test\_%
                 User: 
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: Y
          Create_priv: Y
            Drop_priv: Y
           Grant_priv: N
      References_priv: Y
           Index_priv: Y
           Alter_priv: Y
Create_tmp_table_priv: Y
     Lock_tables_priv: Y
     Create_view_priv: Y
       Show_view_priv: Y
  Create_routine_priv: Y
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: Y
         Trigger_priv: Y
*************************** 3. row ***************************
                 Host: 192.168.85.132
                   Db: db1
                 User: user2
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: N
          Create_priv: N
            Drop_priv: N
           Grant_priv: N
      References_priv: N
           Index_priv: N
           Alter_priv: N
Create_tmp_table_priv: N
     Lock_tables_priv: N
     Create_view_priv: N
       Show_view_priv: N
  Create_routine_priv: N
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: N
         Trigger_priv: N
*************************** 4. row ***************************
                 Host: 192.168.85.133
                   Db: db1
                 User: user2
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: N
          Create_priv: N
            Drop_priv: N
           Grant_priv: N
      References_priv: N
           Index_priv: N
           Alter_priv: N
Create_tmp_table_priv: N
     Lock_tables_priv: N
     Create_view_priv: N
       Show_view_priv: N
  Create_routine_priv: N
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: N
         Trigger_priv: N
*************************** 5. row ***************************
                 Host: %
                   Db: sc
                 User: user3
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: Y
          Create_priv: Y
            Drop_priv: Y
           Grant_priv: N
      References_priv: Y
           Index_priv: Y
           Alter_priv: Y
Create_tmp_table_priv: Y
     Lock_tables_priv: Y
     Create_view_priv: Y
       Show_view_priv: Y
  Create_routine_priv: Y
   Alter_routine_priv: Y
         Execute_priv: Y
           Event_priv: Y
         Trigger_priv: Y
*************************** 6. row ***************************
                 Host: localhost
                   Db: test
                 User: user3
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: Y
          Create_priv: Y
            Drop_priv: Y
           Grant_priv: N
      References_priv: Y
           Index_priv: Y
           Alter_priv: Y
Create_tmp_table_priv: Y
     Lock_tables_priv: Y
     Create_view_priv: Y
       Show_view_priv: Y
  Create_routine_priv: Y
   Alter_routine_priv: Y
         Execute_priv: Y
           Event_priv: Y
         Trigger_priv: Y
6 rows in set (0.00 sec)

ERROR: 
No query specified

mysql>
  • 查看 mysql 库中的 db 表里 db 字段的所有内容
mysql> select db from mysql.db;
+---------+
| db      |
+---------+
| sc      |
| test    |
| test\_% |
| db1     |
| db1     |
| test    |
+---------+
6 rows in set (0.00 sec)

mysql>
  • 查看 mysql 库中的 db 表里 db 和 user 字段的所有内容
mysql> select db,user from mysql.db;
+---------+-------+
| db      | user  |
+---------+-------+
| test    |       |
| test\_% |       |
| db1     | user2 |
| db1     | user2 |
| db1     | user2 |
+---------+-------+
5 rows in set (0.00 sec)

mysql>
  • 查看 mysql 库中的 db 表里 host 字段为 192.168. 开头的所有内容,like 是模糊查询的关键字,where 是指定的一个条件
mysql> select * from mysql.db where host like '192.168.%'\G;
*************************** 1. row ***************************
                 Host: 192.168.133.1
                   Db: db1
                 User: user2
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: N
          Create_priv: N
            Drop_priv: N
           Grant_priv: N
      References_priv: N
           Index_priv: N
           Alter_priv: N
Create_tmp_table_priv: N
     Lock_tables_priv: N
     Create_view_priv: N
       Show_view_priv: N
  Create_routine_priv: N
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: N
         Trigger_priv: N
*************************** 2. row ***************************
                 Host: 192.168.85.132
                   Db: db1
                 User: user2
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: N
          Create_priv: N
            Drop_priv: N
           Grant_priv: N
      References_priv: N
           Index_priv: N
           Alter_priv: N
Create_tmp_table_priv: N
     Lock_tables_priv: N
     Create_view_priv: N
       Show_view_priv: N
  Create_routine_priv: N
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: N
         Trigger_priv: N
*************************** 3. row ***************************
                 Host: 192.168.85.133
                   Db: db1
                 User: user2
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: N
          Create_priv: N
            Drop_priv: N
           Grant_priv: N
      References_priv: N
           Index_priv: N
           Alter_priv: N
Create_tmp_table_priv: N
     Lock_tables_priv: N
     Create_view_priv: N
       Show_view_priv: N
  Create_routine_priv: N
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: N
         Trigger_priv: N
3 rows in set (0.00 sec)

ERROR: 
No query specified

mysql>
  • insert 语句是用来插入数据的
mysql> select * from sc.xxx1;
+------+------+
| id   | name |
+------+------+
|    1 | abc  |
+------+------+
1 row in set (0.00 sec)

mysql> insert into sc.xxx1 values (1, 'abc');
Query OK, 1 row affected (0.00 sec)

mysql> select * from sc.xxx1;
+------+------+
| id   | name |
+------+------+
|    1 | abc  |
|    1 | abc  |
+------+------+
2 rows in set (0.00 sec)

mysql> insert into sc.xxx1 values (1, 'abc');
Query OK, 1 row affected (0.00 sec)

mysql> select * from sc.xxx1;
+------+------+
| id   | name |
+------+------+
|    1 | abc  |
|    1 | abc  |
|    1 | abc  |
+------+------+
3 rows in set (0.00 sec)
  • update 语句是用来修改或者说更新数据的:
mysql> update sc.xxx1 set name='888' where id=1;
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4  Changed: 4  Warnings: 0

mysql> select * from sc.xxx1;
+------+------+
| id   | name |
+------+------+
|    1 | 888  |
|    1 | 888  |
|    1 | 888  |
|    1 | 888  |
+------+------+
4 rows in set (0.00 sec)

mysql> update sc.xxx1 set id=2 where name='888';
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4  Changed: 4  Warnings: 0

mysql> select * from sc.xxx1;
+------+------+
| id   | name |
+------+------+
|    2 | 888  |
|    2 | 888  |
|    2 | 888  |
|    2 | 888  |
+------+------+
4 rows in set (0.00 sec)

mysql>
  • 删除符合条件的行:

将数据库表中,id 为 2 的记录删除

mysql> delete from sc.xxx1 where id=2;
Query OK, 4 rows affected (0.00 sec)

mysql> select * from sc.xxx1;
Empty set (0.00 sec)

mysql>
  • 清空数据,能够把一个表格里的所有数据都清空,但是表结构还存在:
mysql> truncate table db1.t1;
Query OK, 0 rows affected (0.35 sec)

mysql> select * from db1.t1;
Empty set (0.00 sec)

mysql>
  • drop 是用来删除结构的,drop 的删除不仅仅删除数据,会把结构也一并删除,以上这条 drop 就是把 db1 库中的 t1 表给删除掉:
mysql> drop table db1.t1;
Query OK, 0 rows affected (0.04 sec)

mysql> select * from sc.xxx1;
ERROR 1146 (42S02): Table 'sc.xxx1' doesn't exist
  • 这是删除数据库的,同样的也是删除结构:
mysql> drop database sc;
Query OK, 0 rows affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)

mysql>

drop 和 truncate、delete 语句不同的是,前者删除在整个结构,后者仅仅删除结构中的数据。

谨记一点,drop 和 truncate、delete 等语句尽量不要使用,如果需要使用的话记得提前备份数据,并且使用时万分小心看仔细了别删错数据了,如果不小心误操作把一个线上跑的数据库给删了的话,而且又没有备份可恢复,那么就等着被开除或赔偿吧。

8. MySQL数据库备份恢复

【图文教程】MySQL_第25张图片

因为数据的重要性,所以备份与恢复技术是非掌握不可的,在这里介绍一下,备份和恢复数据库的相关操作:

mysqldump 是一个备份的命令,可以备份一个库,也可以备份一个表:

  • 备份库,语法如下:
[root@sc ~]# mysqldump -uroot -p123 mysql >/tmp/mysqlbak.sql
Warning: Using a password on the command line interface can be insecure.
[root@sc ~]#

在这里插入图片描述

  • 恢复库,将备份文件里的内容重定向到一个空的数据库中,语法如下:
[root@sc ~]# mysql -uroot -p123 -e "create database mysql2"
Warning: Using a password on the command line interface can be insecure.
[root@sc ~]# mysql -uroot -p123 mysql2 < /tmp/mysqlbak.sql
Warning: Using a password on the command line interface can be insecure.
[root@sc ~]#

在这里插入图片描述

  1. 进入到mysql2中,可以看到数据已经恢复到这个库中了:
[root@sc ~]# mysql -uroot -p123 mysql2
Warning: Using a password on the command line interface can be insecure.
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 43
Server version: 5.6.43 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show tables;
+---------------------------+
| Tables_in_mysql2          |
+---------------------------+
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
28 rows in set (0.00 sec)

mysql>

从以上备份和恢复数据库可见,其实就是一个重定向的应用,重定向出去叫备份,重定向进来叫恢复。

  • 备份表,除了备份整个数据库之外,还能针对数据库中的某个表进行备份,指定库名和表名即可,语法如下:
[root@sc ~]# mysqldump -uroot -p123 mysql user > /tmp/user.sql
Warning: Using a password on the command line interface can be insecure.
[root@sc ~]#

在这里插入图片描述

  • 恢复表,和恢复库一样的,把备份的文件内容重定向回去,语法如下:
[root@sc ~]# mysql -uroot -p123 mysql2 < /tmp/user.sql
Warning: Using a password on the command line interface can be insecure.
[root@sc ~]#

在这里插入图片描述

  • 备份所有的库,如果 mysql 中有很多数据库,一个个去备份太麻烦,所以需要能够备份所有数据库的语句,语法如下:

-A是all,所有的意思

[root@sc ~]# mysqldump -uroot -p123 -A >/tmp/mysql_all.sql
Warning: Using a password on the command line interface can be insecure.
[root@sc ~]#

在这里插入图片描述

  1. 可以查看到这个备份文件就比较大了,有1.3M
[root@sc ~]# du -sh /tmp/mysql_all.sql 
1.3M	/tmp/mysql_all.sql
[root@sc ~]#
  • 只备份表结构,如果你不需要数据的情况下,就可以只备份表结构,使用 -d 选项,语法如下:
[root@sc ~]# mysqldump -uroot -p123 -d mysql2 > /tmp/mysql2.sql
Warning: Using a password on the command line interface can be insecure.
[root@sc ~]#

在这里插入图片描述

然后你可以使用less查看备份文件的内容,会发现没有insert语句只有drop和create语句

mysqldump 只适合数据量不大的备份,如果数据库中的数据库很大的话,就不适合使用mysqldump 了,使用 mysqldump 的话备份会很慢,关于如何备份数量大的数据库可以参考以下扩展内容

9. MariaDB安装

MariaDB 官网:https://mariadb.org/

讲义

安装 mariadb 二进制的免编译包:

1. cd /usr/local/src
2. wget https://mirrors.tuna.tsinghua.edu.cn/mariadb//mariadb-10.2.23/bintar-linux-glibc_214-x86_64/mariadb-10.2.23-linux-glibc_214-x86_64.tar.gz
3. tar zxvf mariadb-10.2.23-linux-glibc_214-x86_64
4. mv mariadb-10.2.23-linux-glibc_214-x86_64 /usr/local/mariadb
5. cd /usr/local/mariadb
6. ./scripts/mysql_install_db --user=mysql --basedir=/usr/local/mariadb/ --datadir=/data/mariadb
7. cp support-files/my-small.cnf /usr/local/mariadb/my.cnf
8. vi /usr/local/mariadb/my.cnf //定义basedir和datadir
9. cp support-files/mysql.server /etc/init.d/mariadb
10. vim /etc/init.d/mariadb //定义basedir、datadir、conf以及启动参数
11. /etc/init.d/mariadb start
  • 使用 wget 下载 MariaDB
[root@sc src]# wget https://mirrors.tuna.tsinghua.edu.cn/mariadb//mariadb-10.4.7/bintar-linux-systemd-x86_64/mariadb-10.4.7-linux-systemd-x86_64.tar.gz
  • 解包
[root@sc src]# tar zxvf mariadb-10.4.7-linux-systemd-x86_64.tar.gz
  • 移动到 /user/local/ 下并更名为 mysql(默认都改成mysql)
[root@sc src]# mv mariadb-10.4.7-linux-systemd-x86_64 /usr/local/mysql
  • 进入到 /usr/local/mysql 目录下,创建用户 mysql,创建存放 mysql 数据库 /data/mysql,指定数据库的属主属组
[root@test01 local]# cd mariadb/
[root@test02 mysql]# useradd mysql
[root@test02 mysql]# mkdir -p /data/mysql
[root@test02 mysql]# chown -R mysql:mysql /data/mysql
  • 使用 mysql 用户进行初始化在 /data/ 目录下生成一个库,验证一下是否成功
[root@sc mysql]# ./scripts/mysql_install_db --user=mysql --datadir=/data/mysql
[root@sc mysql]# echo $?
0


需要安装这些包:

yum install libnuma.so.1
yum install numactl
yum install-y libaio
yum install-y libaio-devel
  • 拷贝 mysql 启动脚本
[root@sc mysql]# cp support-files/mysql.server /etc/init.d/mysqld
  • 编辑 mysql 启动脚本
[root@sc mysql]# vim /etc/init.d/mysqld

basedir=/usr/local/mysql
datadir=/data/mysql
  • 编辑 mysql 配置文件
[root@test02 ~]# vim /etc/my.cnf

datadir=/data/mysql
socket=/tmp/mysql.sock
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
  • 启动 mysqld 服务
[root@test02 mysql]# /etc/init.d/mysqld start
  • 查看 mysqld 进程
[root@test02 mysql]# ps aux |grep mysqld
root      9859  0.0  0.1 115436  1768 ?        S    22:50   0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/data/mysql --pid-file=/data/mysql/test02.pid
mysql     9944  0.2  7.3 1254092 74316 ?       Sl   22:50   0:00 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/data/mysql --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/data/mysql/mysql.log --pid-file=/data/mysql/test02.pid --socket=/tmp/mysql.sock
root      9986  0.0  0.0 112708   988 pts/0    S+   22:54   0:00 grep --color=auto mysqld
  • 检查是否有3306端口
[root@test02 mysql]# netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      5977/sshd           
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      6119/master         
tcp6       0      0 :::3306                 :::*                    LISTEN      9944/mysqld         
tcp6       0      0 :::22                   :::*                    LISTEN      5977/sshd           
tcp6       0      0 ::1:25                  :::*                    LISTEN      6119/master         
  • 将 mysqld 设置为开机启动
chkconfig --add mysqld     #将mysql添加到开机启动
chkconfig --list           #查看开机启动列表

Note: This output shows SysV services only and does not include native
      systemd services. SysV configuration data might be overridden by native
      systemd configuration.

      If you want to list systemd services use 'systemctl list-unit-files'.
      To see services enabled on particular target use
      'systemctl list-dependencies [target]'.

mysqld         	0:off	1:off	2:on	3:on	4:on	5:on	6:off
netconsole     	0:off	1:off	2:off	3:off	4:off	5:off	6:off
network        	0:off	1:off	2:on	3:on	4:on	5:on	6:off

10. MariaDB慢查询日志

  • 为什么要配置慢查询日志?
目的是为了帮助我们分析MariaDB的瓶颈点。
  • 如何配置?
1)进入MariaDB里面执行:

MariaDB [(none)]> show variables like 'slow%';    #显示变量如 “慢查询”
+---------------------+-----------------+
| Variable_name       | Value           |
+---------------------+-----------------+
| slow_launch_time    | 2               |
| slow_query_log      | OFF             |
| slow_query_log_file | backup-slow.log |
+---------------------+-----------------+
3 rows in set (0.034 sec)



MariaDB [(none)]> show variables like 'datadir';  #显示变量如 “数据目录”
+---------------+--------------+
| Variable_name | Value        |
+---------------+--------------+
| datadir       | /data/mysql/ |
+---------------+--------------+
1 row in set (0.002 sec)



MariaDB [(none)]> show variables like 'long%';    #显示变量如 “超时时间”
+-----------------+-----------+
| Variable_name   | Value     |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
1 row in set (0.002 sec)



2)打开配置文件/etc/my.cnf,编辑,增加:
	slow_query_log = ON   #慢查询日志打开
	slow_query_log_file = /data/mysql/aminglinux01-slow.log  #慢查询日志的路径
	long_query_time = 2   #慢查询时不超过23)重启服务
    /etc/init.d/mysqld start

4)模拟慢查询
	select sleep(5);  #测试慢查询 5 秒钟

5)查看慢查询日志:
	cat /data/mysql/aminglinux01-slow.log  #慢查询日志有没有记录
  • 扩展知识
show processlist;       #显示有哪些进程在运行,最多显示100条

show full processlist;  #显示有哪些进程在运行,全部列出来

mysql -uroot -pxxxx -e "show processlist"  #举例语句

11. MySQL扩展

1.mysql5.5源码编译安装 http://www.aminglinux.com/bbs/thread-1059-1-1.html
2.mysql5.7二进制包安装(变化较大) http://www.apelearn.com/bbs/thread-10105-1-1.html
3.mysql5.7 root密码更改 http://www.apelearn.com/bbs/thread-7289-1-1.html
4.myisam 和innodb引擎对比 http://www.pureweber.com/article/myisam-vs-innodb/
5.mysql 配置详解: http://blog.linuxeye.com/379.html
6.mysql调优: http://www.aminglinux.com/bbs/thread-5758-1-1.html
7.同学分享的亲身mysql调优经历: http://www.apelearn.com/bbs/thread-11281-1-1.html
8.SQL语句教程 http://www.runoob.com/sql/sql-tutorial.html
9.什么是事务?事务的特性有哪些? http://blog.csdn.net/yenange/article/details/7556094
10.根据binlog恢复指定时间段的数据 https://blog.csdn.net/lilongsy/article/details/74726002
11.mysql字符集调整 http://xjsunjie.blog.51cto.com/999372/1355013
12.如何取消mysql授权并删除用户 https://www.cnblogs.com/guigujun/p/6265891.html

直播课:
mysql的版本:https://www.cnblogs.com/ivictor/p/9807284.html
mariadb的版本:https://downloads.mariadb.org/
主从:
https://blog.csdn.net/xiaoyi23000/article/details/80521423
https://blog.csdn.net/u013399093/article/details/70568837
https://www.cnblogs.com/abobo/p/4242417.html
MySQL Cloud Service 总结 http://isky000.com/database/mysql-perfornamce-tuning-cache-parameter

MySQL主从
1.有的同学,遇到主从不能正常同步,提示uuid相同的错误。这是因为克隆机器导致。
https://www.2cto.com/database/201412/364479.html
2.不停库不锁表在线主从配置
http://seanlook.com/2015/12/14/mysql-replicas/
3.主从不同步
http://www.rfyy.net/archives/2309.html
http://blog.51cto.com/storysky/259280
4.主主
关于 auto_increment https://blog.csdn.net/leshami/article/details/39779509
5.http://www.cnblogs.com/ygqygq2/p/6045279.html
6.mysql-proxy 实现读写分离 http://blog.51cto.com/zzclinux/1980487
7.mysql-proxy类似的产品有:
8.mycat 基于阿里的开源软件cobar,官网 www.mycat.io,https://my.oschina.net/ruoli/blog/1789370
9.mycat实现分库分表 https://www.cnblogs.com/joylee/p/7513038.html
10.atlas 出自于360,不维护不更新了 https://blog.csdn.net/AnPHPer/article/details/80566385
11.mysql环形主从 http://ask.apelearn.com/question/11437
12.mysql架构演变 http://www.aminglinux.com/bbs/thread-8025-1-1.html
13.MHA架构 http://blog.51cto.com/xiaoshuaigege/2060768
14.比较复杂的mysql集群架构 http://ask.apelearn.com/question/17026

直播课:
xtrabackup --> innobackupex
mariadb备份和恢复
几篇和mysql主从有关的文章 关键词 GTID
https://blog.csdn.net/xiaoyi23000/article/details/80521423
https://blog.csdn.net/u013399093/article/details/70568837
https://www.cnblogs.com/abobo/p/4242417.html

了解几个关键词
读写分离
分库分表

你可能感兴趣的:(Linux,【图文教程】,Linux,MySQL)