1.1RDBMS专业名词
常见的关系型数据库管理系统:
- MySQL:MySQL,MariaDB,Percona-Server
- PostgreSQL:简称为pgsql
- Oracle
- MSSQL
- **SQL:**Structure Query Language,结构化查询
**SQL:**Structure Query Language,结构化查询语言
**约束:**constraint,向数据表提供的数据要遵守的限制
主键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。且必须提供数据,不能为空(NOT NULL)。
一个表只能存在一个
惟一键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。允许为空(NULL)
一个表可以存在多个
外键约束:一个表中的某字段可填入数据取决于另一个表的主键已有的数据
检查性约束
**索引:**将表中的一个或多个字段中的数据复制一份另存,并且这些数据需要按特定次序排序存储
1.2 关系型数据库的常见组件
关系型数据库的常见组件有:
数据库:database
表:table,由行(row)和列(column)组成
索引:index
视图:view
用户:user
权限:privilege
存储过程:procedure
存储函数:function
触发器:trigger
事件调度器:event scheduler
1.3 SQL语句
SQL语句有三种类型:
- DDL:Data Defination Language,数据定义语言
- DML:Data Manipulation Language,数据操纵语言
- DCL:Data Control Language,数据控制语言
SQL语句类型 | 对应操作 |
---|---|
DDL | CREATE:创建 DROP:删除 ALTER:修改 |
DML | INSERT:向表中插入数据 DELETE:删除表中数据 UPDATE:更新表中数据 SELECT:查询表中数据 |
DCL | GRANT:授权 REVOKE:移除授权 |
MySQL安装
安装所需MySQL安装包
2.1 配置MySQL的yum源
安装wget
wget -O /usr/src/mysql57-community-release-el7-10.noarch.rpm \
http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm[root@rl ~]cd /usr/src/
[root@rl src]#rpm -ivh mysql57-community-release-el7-10.noarch.rpm//会出现MySQL的yum仓库
[root@rl src]# cd /etc/yum.repos.d/
[root@rl yum.repos.d]# ls
mysql-community.repo redhat.repo
mysql-community-source.repo server.repo
安装所需MySQL安装包
http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/
[root@rl ~]# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/mysql-community-server-5.7.43-1.el7.x86_64.rpm
[root@rl~]# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/mysql-community-common-5.7.43-1.el7.x86_64.rpm
[root@rl ~]# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/mysql-community-devel-5.7.43-1.el7.x86_64.rpm
[root@rl~]# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/mysql-community-client-5.7.43-1.el7.x86_64.rpm
[root@rl~]# wget http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/mysql-community-libs-5.7.43-1.el7.x86_64.rpm
[root@rl ~]# ls
mysql-community-client-5.7.43-1.el7.x86_64.rpm
mysql-community-common-5.7.43-1.el7.x86_64.rpm
mysql-community-devel-5.7.43-1.el7.x86_64.rpm
mysql-community-libs-5.7.43-1.el7.x86_64.rpm
mysql-community-server-5.7.43-1.el7.x86_64.rpm
//软件包已经成功下载到本地
//安装软件包
[root@rl ~]# yum -y localinstall *.rpm
2.2 mysql配置
启动MySQL并设置开机自启
[root@rl ~]# systemctl enable --now mysqld
[root@rl ~]# systemctl status mysqld
查看3306是否已经监听
[root@rl~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 80 *:3306 *:*
过滤查看MySQL密码(此密码属于一次性密码,用来给数据库设置新密码用)
[root@rl ~]# grep password /var/log/mysqld.log
2023-08-29T15:49:33.735173Z 1 [Note] A temporary password is generated for root@localhost: 5IjfwC%2u_6H
[root@rl~]# mysql -uroot -p'5IjfwC%2u_6H' //使用临时命令进入MySQLmysql> set password = password('Zhouwei123!'); //设置新的密码
Query OK, 0 rows affected, 1 warning (0.00 sec)mysql>
[root@rl ~]# rpm -qa|grep mysql
mysql-community-client-5.7.43-1.el7.x86_64
mysql57-community-release-el7-10.noarch //卸载掉它防止自动更新
mysql-community-libs-5.7.43-1.el7.x86_64
mysql-community-server-5.7.43-1.el7.x86_64
mysql-community-common-5.7.43-1.el7.x86_64
mysql-community-devel-5.7.43-1.el7.x86_64
//为避免mysql自动升级,这里需要卸载最开始安装的yum源
[root@rl ~]# rpm -e mysql57-community-release //删除
[root@rl ~]# rpm -qa|grep mysql
mysql-community-client-5.7.43-1.el7.x86_64
mysql-community-libs-5.7.43-1.el7.x86_64
mysql-community-server-5.7.43-1.el7.x86_64
mysql-community-common-5.7.43-1.el7.x86_64
mysql-community-devel-5.7.43-1.el7.x86_64
2.3 mysql的程序组成
- 客户端
- mysql:CLI交互式客户端程序
- mysql_secure_installation:安全初始化,强烈建议安装完以后执行此命令
- mysqldump:mysql备份工具
- mysqladmin
- 服务器端
- mysqld
安全初始化
[root@rl~]# mysql_secure_installation
Securing the MySQL server deployment.
Enter password for user root:
The 'validate_password' plugin is installed on the server.
The subsequent steps will run with the existing configuration
of the plugin.
Using existing password for root.Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) : //回车... skipping.
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.Disallow root login remotely? (Press y|Y for Yes, any other key for No) :
//回车
... skipping.
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
- Dropping test database...
Success.
- Removing privileges on test database...
Success.Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.All done!
2.4 MySQL工具的使用
//语法:mysql [OPTIONS] [database]
//常用的OPTIONS:
-uUSERNAME //指定用户名,默认为root
-hHOST //指定服务器主机,默认为localhost,推荐使用ip地址
-pPASSWORD //指定用户的密码
-P# //指定数据库监听的端口,这里的#需用实际的端口号代替,如-P3307
-V //查看当前使用的mysql版本
-e //不登录mysql执行sql语句后退出,常用于脚本
查看MySQL版本
mysql -V
查看数据库
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| rl |
| sys |
+--------------------+
5 rows in set (0.00 sec
如果想要用一台master主机连接RHEL8的数据库
先在主机上面安装mariadb作为客户端
[root@master ~]# yum -y install mariadb
授权master主机的tom用户登录数据库
mysql> grant all on *.* to 'tom'@'192.168.198.112' identified by 'Zhouwei123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)
关闭防火墙(主控RHEL8和受控master的防火墙都需要关闭)
[root@master ~]# systemctl disable --now firewalld
通过受控master连接主控RHEL8的数据库
[root@master ~]# mysql -utom -pZhouwei123! -h192.168.198.130
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.43 MySQL Community Server (GPL)Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
2.5 真实机workbench链接虚拟机数据库
本地使用workbench连接数据库
使用真实机的cmd查看ip
C:\Users\zw>ipconfing
在linux上面的MySQL添加访问权限
mysql> grant all on *.* to tom@192.168.198.1 identified by 'Zhouwei1
123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
测试连接成功
查看linux数据库的权限
mysql> show grants;
mysql> show grants for 'tom'@192.168.198.1;
2.7 服务器监听的两种socket地址
socket类型 | 说明 |
---|---|
ip socket | 默认监听在tcp的3306端口,支持远程通信 |
unix sock | 监听在sock文件上(/tmp/mysql.sock,/var/lib/mysql/mysql.sock) 仅支持本地通信 server地址只能是:localhost,127.0.0.1 |
3.MySQL数据库操作
3.1 DDL操作
3.1.1 数据库操作
创建数据库
mysql> create database if not exists rl; //创建数据库
删除数据库
mysql> drop database if exists rl;
3.1.2 表操作
mysql> use rl; //进入数据库
show tables; //查看表
drop table zhouwei; 删除表
3.1.3 用户操作
mysql用户帐号由两部分组成,如’USERNAME’@‘HOST’,表示此USERNAME只能从此HOST上远程登录
这里(‘USERNAME’@‘HOST’)的HOST用于限制此用户可通过哪些主机远程连接mysql程序,其值可为:
- IP地址,如:172.16.12.129
- 通配符
- %:匹配任意长度的任意字符,常用于设置允许从任何主机登录
- _:匹配任意单个字符
-
//数据库用户创建
//语法:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];
//创建数据库用户zhouwei
mysql> CREATE USER 'zhouwei'@'192.168.198.130' IDENTIFIED BY 'zhouwei123!';
Query OK, 0 rows affected (0.00 sec)//使用新创建的用户和密码登录
[root@localhost ~]# mysql -uzhouwei -pzhouwei123! -h192.168.198.130
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 6
Server version: 5.7.23 MySQL Community Server (GPL)Copyright (c) 2000, 2018, 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>
-
//删除数据库用户
-
//语法:DROP USER 'username'@'host'; mysql> DROP USER 'rl'@'192.168.198.130'; Query OK, 0 rows affected (0.00 sec)
3.1.4 查看命令SHOW
mysql> SHOW CHARACTER SET; //查看支持的所有字符集
+----------+---------------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+---------------------------------+---------------------+--------+
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_ci | 1 |
......
......
mysql> SHOW ENGINES; //查看当前数据库支持的所有存储引擎
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine | Support | Comment
| Transactions | XA | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| InnoDB | DEFAULT | Supports transactions, row-level locking, and
foreign keys | YES | YES | YES |
| MRG_MYISAM | YES | Collection of identical MyISAM tables
| NO | NO | NO |
| MEMORY | YES | Hash based, stored in memory, useful for temporary tables | NO | NO | NO |
| BLACKHOLE | YES | /dev/null storage engine (anything you write to it disappears) | NO | NO | NO |
| MyISAM | YES | MyISAM storage engine | NO | NO | NO |
| CSV | YES | CSV storage engine | NO | NO | NO |
| ARCHIVE | YES | Archive storage engine | NO | NO | NO |
| PERFORMANCE_SCHEMA | YES | Performance Schema | NO | NO | NO |
| FEDERATED | NO | Federated MySQL storage engine | NULL | NULL | NULL |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.00 sec)
mysql> show databases; //查看数据库信息
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| zhouwei |
+--------------------+
5 rows in set (0.02 sec)
mysql> show tables from zhouwei; //不进入某数据库而列出其包含的所有表
+-------------------+
| Tables_in_zhouwei |
+-------------------+
| zhouwei |
+-------------------+
1 row in set (0.00 sec)
//查看表结构
//语法:DESC [db_name.]table_name;
mysql> desc zhouwei.zhouwei;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| name | varchar(100) | NO | | NULL | |
| age | tinyint(4) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.03 sec)
————————————————
//查看某表的创建命令
//语法:SHOW CREATE TABLE table_name;
//查看某表的状态
//语法:SHOW TABLE STATUS LIKE 'table_name'\G mysql> show table status like 'rl'\G //查看zhouwei表的状态
3.1.5 获取帮助
//获取命令使用帮助
//语法:HELP keyword;
4 DML操作
DML操作包括增(INSERT)、删(DELETE)、改(UPDATE)、查(SELECT),均属针对表的操作。
4.1 INSERT语句
//DML操作之增操作insert
//语法:INSERT [INTO] table_name [(column_name,...)] {VALUES | VALUE} (value1,...),(...),...
```mysql> use zhouwei;
Database changed
mysql> insert into zhouwei(id,name,age) value(1,'tom',20);
Query OK, 1 row affected (0.01 sec)mysql> insert into zhouwei (id,name,age) values(2,'jerry',23),(3,'zhouwei',25),(4,'lisi',NULL);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
4.2 SELECT语句
字段column表示法
条件判断语句WHERE
表示符 | 代表什么? |
---|---|
* | 所有字段 |
as | 字段别名,如col1 AS alias1 当表名很长时用别名代替 |
条件判断语句WHERE
操作类型 | 常用操作符 |
---|---|
操作符 | >,<,>=,<=,=,!= BETWEEN column# AND column# LIKE:模糊匹配 RLIKE:基于正则表达式进行模式匹配 IS NOT NULL:非空 IS NULL:空 |
条件逻辑操作 | AND OR NOT |
ORDER BY:排序,默认为升序(ASC)
ORDER By | 意义 |
ORDER BY ‘column_name’ | 根据column_name进行升序排序 |
ORDER BY ‘column_name’ DESC | 根据column_name进行降序排序 |
ORDER BY ’column_name’ LIMIT 2 | 根据column_name进行升序排序 并只取前2个结果 |
ORDER BY ‘column_name’ LIMIT 1,2 | 根据column_name进行升序排序 并且略过第1个结果取后面的2个结果0 |
4.3 update语句
//DML操作之改操作update
//语法:UPDATE table_name SET column1 = new_value1[,column2 = new_value2,...] [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
4.4 delete语句
//DML操作之删操作delete
//语法:DELETE FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
4.5 truncate语句
语句类型 | 特点 |
delete | DELETE删除表内容时仅删除内容,但会保留表结构 DELETE语句每次删除一行,并在事务日志中为所删除的每行记录一项 可以通过回滚事务日志恢复数据 非常占用空间 |
truncate | 删除表中所有数据,且无法恢复 表结构、约束和索引等保持不变,新添加的行计数值重置为初始值 执行速度比DELETE快,且使用的系统和事务日志资源少 通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放 对于有外键约束引用的表,不能使用TRUNCATE TABLE删除数据 不能用于加入了索引视图的表 |
4.6 DCL操作
4.6.1 创建授权grant
权限类型(priv_type)
指定要操作的对象db_name.table_name
表示方式 | 意义 |
---|---|
. | 所有库的所有表 |
db_name | 指定库的所有表 |
db_name.table_name | 指定库的指定表 |
权限类型 | 代表什么? |
---|---|
ALL | 所有权限 |
SELECT | 读取内容的权限 |
INSERT | 插入内容的权限 |
UPDATE | 更新内容的权限 |
DELETE | 删除内容的权限 |
WITH GRANT OPTION:被授权的用户可将自己的权限副本转赠给其他用户,说白点就是将自己的权限完全复制给另一个用户。不建议使用。
mysql> show databases
-> ;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| zhouwei |
+--------------------+
//授权wangqing用户在数据库本机上登录访问所有数据库
mysql> grant all on *.* to 'zhouwei'@'localhost' identified by 'Zhouuwei123!';
Query OK, 0 rows affected, 1 warning (0.02 sec)mysql> grant all on *.* to 'zhouwei'@'192.168.198.112' identified by 'Zhouwei123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)//授权zhouwei用户在192.168.198.112上远程登录访问zhouwei数据库
mysql> grant all on zhouwei.* to 'zhouwei'@'192.168.198.112' identified by 'Zhouwei123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)//授权zhouwei用户在所有位置上远程登录访问zhouwei数据库
mysql> grant all on *.* to 'zhouwei'@'%' identified by 'Zhouwei123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)在受控机(master)查看是否有权限
[root@master ~]# mysql -uzhouwei -pZhouwei123! -h192.168.198.130;
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.43 MySQL Community Server (GPL)Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
4.6.2 查看授权
//查看当前登录用户的授权信息
mysql> show grants;
//查看指定用户zhouwei的授权信息
mysql> show grants for zhouwei;
4.6.3 取消授权REVOKE
//语法:REVOKE priv_type,... ON db_name.table_name FROM 'username'@'host';
mysql> revoke all on *.* from 'rl'@'192.168.198.112';
注意:mysql服务进程启动时会读取mysql库中的所有授权表至内存中
- GRANT或REVOKE等执行权限操作会保存于表中,mysql的服务进程会自动重读授权表,并更新至内存中
- 对于不能够或不能及时重读授权表的命令,可手动让mysql的服务进程重读授权表
mysql> flush privileges;