【MySQL】数据库的操作
目录
作者:爱写代码的刚子
时间:2024.3.2
前言:本篇博客主要记录数据库的操作
创建数据库
-
**create database +数据库名字;**本质就是在/var/lib/mysql里创建一个目录
-
**drop database +数据库名字;**本质就是删除目录
-
create database if not exists +数据库名字带上if not exist选项表示没有该数据库就进行创建

数据库的编码集和校验集
- 数据库编码集:数据库未来存储数据
- 数据库校验集:支持数据库,进行字段比较使用的编码,本质也是一种读取数据库中数据的采用的编码格式
- 数据库无论对数据做任何操作,都必须保证操作和编码必须是编码一致的!
查看系统默认字符集以及校验规则
- show variables like 'character_set_database'; 查看数据库默认(配置文件决定了)的字符集
- **show variables like 'collation_database';**查看数据库默认的校验规则

查看数据库支持的字符集
- show charset;

查看数据库支持的字符集校验规则
- show collation;

- 数据库里面的db.opt文件中存放数据库的编码集和校验规则

创建数据库,并设置其编码集:
- create database 数据库名字 charset=utf8;
- create database d3 character set utf8;

我们可以在/var/lib/mysql对应数据库目录里的db.opt查看数据库的编码集和校验规则。
- **create database d4 charset=utf8 collate utf8_general_ci;**创建数据库并设置其编码集和校验规则


校验规则对数据库的影响
- 创建两个数据库,编码规则相同,但是校验规则不同:
- utf8_ general_ ci不区分大小写
- utf8_bin区分大小写

- 建表并查看表:

- 向表中插入数据:

- **select * from person;**查看表中的所有数据

- **select * from person where name='a';**查看表中名为a的数据

这里我们发现数据库test1中的校验规则为utf8_ general_ ci ,并不区分大小写
- 使用数据库test2做验证:

这里我们发现数据库test2中的校验规则为utf8_bin ,区分大小写
- **select * from person order by name;**使用order by进行排序
使用不同的校验规则排序产生的结果并不相同:
test1:

test2:

数据库的删除
- drop database if exists +数据库的名字删除数据库,if exists表示如果存在就进行删除

执行删除之后的结果:
- 数据库内部看不到对应的数据库
- 对应的数据库文件夹被删除,级联删除,里面的数据表全部被删
不要随便删除数据库!!!
-
**use +数据库名;**使用数据库
-
**select database();**查看当前在哪个数据库中

- **alter database 数据库名字 charset=gbk collate gbk_chinese_ci;**修改数据库的编码集和校验规则

- show create database 数据库名字显示创建数据库的命令

说明:
- MySQL 建议我们关键字使用大写,但是不是必须的。
- 数据库名字的反引号``,是为了防止使用的数据库名刚好是关键字。
- /* !40100 default... */这个不是注释,表示当前mysql版本大于4.01版本,就执行这句话

数据库的备份和恢复
备份
- mysqldump -P3306 -uroot -p -B test1 > test1.sql将数据库进行备份

- test.sql里面存放的并不是数据,而是我们历史上使用的数据库的命令

还原
- **source /root/MySQL/test1.sql;**恢复备份了的数据库


不备份整个数据库,而是备份其中的表
- mysqldump -u root -p 数据库名 表名1 表名2 > mysql.sql备份数据库其中的表
- mysqldump -u root -p -B 数据库名1 数据库名2 ... > 数据库存放的路径同时备份多个数据库
注意:如果备份一个数据库时,没有带上-B参数, 在恢复数据库时,需要先创建空数据库,然后使用数据库,再使用source来还原。
带了-B选项,.sql文件中会添加create database ...的选项,所以不用自己创建一个空的数据库
查看连接情况
- **show processlist;**查看数据库有哪些人在使用

可以告诉我们当前有哪些用户连接到我们的MySQL,如果查出某个用户不是自己正常登陆的,很有可能自己的数据库被人入侵了。以后发现自己数据库比较慢时,可以用这个指令来查看数据库连接情况。