学习前言
最近大二要开始学MySQL数据库了,赶快来复习一下啊!🙏🙏🙏
1. MySQL的数据类型
- 整数类型
数据类型 | 字节数 |
---|---|
tinyint(n) | 1 |
smallint(n) | 2 |
mediumint(n) | 3 |
int(n) | 4 |
bigint(n) | 8 |
- 浮点类型
数据类型 | 字节数 |
---|---|
float(n, d) | 8位单精度,4字节 |
double(n, d) | 16位双精度,8字节 |
- 字符类型
数据类型 | 字节数 |
---|---|
char(n) | 固定长度,255字符 |
tinytext | 可变长度,255字符 |
varchar(n) | 可变长度,65535字符 |
text | 可变长度,65535字符 |
mediumtext | 可变长度, 2 24 − 1 2^{24}-1 224−1字符 |
longtext | 可变长度, 2 32 − 1 字 符 2^{32}-1字符 232−1字符 |
- 日期类型
数据类型 | 含义 |
---|---|
date | 日期,年月日 |
time | 时间,时分秒 |
datetime | 日期时间,年月日+时分秒 |
timestamp | 时间戳 |
2. 创建与删除数据库
- 创建数据库的SQL语句:
create database 数据库名 default character set 字符编码;
如:
create database test default character set utf8;
再用show databases;
SQL语句查看所有的数据库。
还可以使用select schema_name, default_character_set_name from information_schema.schemata where schema_name = 'test';
查看test数据库的编码情况。
- 删除数据库
drop database 数据库名;
如:
drop database test;
3. 备份及回复数据库
备份数据
在管理员命令下的cmd中mysql的bin目录,命令如下:
- 备份数据库
mysqldump -u root -h 127.0.0.1 -p 数据库名>备份路径
- 备份数据库中的表
mysqldump -u root -h 127.0.0.1 -p 数据库名 表名>备份路径
- 备份所有数据库
mysqldump -u root -h 127.0.0.1 -p --all-databases>备份路径
恢复数据
mysql -u root -h 127.0.0.1 -p 数据库名<备份的数据库路径
4. 表操作
1. 创建与删除
- 创建
create table 表名(
列名 类型,
列名 类型,
。。。
)
如:
use test; -- 使用哪个数据库
-- 创建数据库
create table students(
stu_id int,
stu_name varchar(8),
gender varchar(2)
);
-- 查看数据库中的表
show tables;
- 删除
drop table 表名;
如:
drop table students; -- 删除表
show tables; -- 查看表
2. 修改表名与列名
- 修改表名
alter table 之前的表名 rename 新的表名;
如:
alter table students rename s1; -- 修改表名
show tables;
- 修改列名
alter table 表名 change column 之前的列名 新列名 数据类型
如:
alter table s1 change column gender sex varchar(4);
3. 添加与删除列
- 添加列
alter table 表名 add column 添加的列名 数据类型
如:
alter table s1 add column score int(4);
- 删除列
alter table 表名 drop column 列名;
如:
alter table s1 drop column score;
4. 修改列数据类型
alter table 表名 modify 列名 新的数据类型;
如:
alter table s1 modify stu_id int(12);