本篇介绍SQL的数据库定义语言DDL,主要有数据库的增删改用、表的增删改查,并且配套有MySQL实操练习。
01 数据库的增删查用
1.1 基本语法
-- 查询数据库
SHOW DATABASES; -- 查询所有数据库
SELECT DATABASE(); -- 查询当前使用的数据库(要先使用数据库,再查询)
-- 增加数据库
CREATE DATABASE database_name;
CREATE DATABASE [IF NOT EXISTS] database_name [DEFAULT CHERSET character_set][COLLATE sort_rule]; -- if not exists 不容易报错
-- 删除数据库
DROP DATABASE database_name;
DROP DATABASE [IF EXISTS] database_name;
-- 使用数据库
USE database_name;
1.2 MySQL实操
-
全局搜索MySQL Workbench 8.0 CE,打开。
-
新建一个连接MySQL Class,打开。
- 在界面中进行操作。运行代码:选中要运行的代码,Ctrl+Shift+Enter即可(单行Crtl+Enter即可)
-
使用
-
查询
-
增加
-
删除
02 表的增删改查
2.1 基本语法
2.1.1 表的查询
-- 查询表(当前数据库的所有表)
show tables;
-- 查询表结构
desc table_name;
-- 查询表的建表语句
show create table table_name;
2.1.2 表的创建
create table [if not exists] 表名 (
列名1 列1类型 [comment 列1注释] -- comment声明
, 列名2 列2类型 [comment 列2注释]
, ...
) [comment 表注释];
2.1.3 表的数据类型
- 数值类型
- 字符串类型
- 日期时间类型
2.1.4 表的修改
-- 修改表名
ALTER TABLE 表名 RENAME TO 新表名;
-- 添加列
ALTER TABLE 表名 ADD 列名 类型 [COMMENT 注释][约束];
-- 修改列
ALTER TABLE 表名 MODIFY 列名 新类型; -- 修改数据类型
ALTER TABLE 表名 CHANGE 旧列名 新列名 类型 [COMMENT 注释][约束]; -- 修改字段名和字段类型
-- 删除列
ALTER TABLE 表名 DROP 列名;
2.1.5 表的删除
DROP TABLE [IF EXISTS] 表名; -- 删除表
TRUNCATE TABLE 表名; -- 删除表,再重新创建该表
2.2 MySQL实操
2.2.1 表的查询
use world;
show tables;
desc city;
show create table city;
2.2.2 表的创建
如:创建学生表student(MySQL)
表结构 | 备注 |
---|---|
编号 | 纯数字 |
学号 | 字符串类型,长度不超过8 |
姓名 | 字符串类型,长度不超过10 |
性别 | 男/女,1个汉字 |
年龄 | 大于0的整数 |
身份证号 | 18位,身份证中有X |
出生日期 | 年月日 |
班级 | 字符串类型,长度不超过5 |
create database if not exists test;
use test;
drop table if exists student;
-- 创建表
create table student (
id int comment "编号"
, s_num varchar(8) comment "学号"
, s_name varchar(10) comment "姓名"
, gender char(1) comment "性别"
, age tinyint unsigned comment "年龄"
, id_card char(18) comment "身份证号"
, birth_date date comment "出生日期"
, class varchar(5) comment "班级"
) comment "学生表";
desc student; -- 查询表结构
show create table student; -- 查询建表语句
2.2.3 表的修改
-- 增加列
alter table student add eng_name varchar(10) comment "英文名";
desc student;
-- 修改列
alter table student modify s_num varchar(12); -- 将s_num列修改为最长不超过12的字符串类型
alter table student change s_num s_number varchar(12) comment "学号"; -- 将s_num改为s_number,字符串类型,长度不超过8
desc student;
-- 删除列
alter table student drop eng_name;
-- 修改表名
alter table student rename to stu_tb;
show tables;
2.2.4 表的删除
truncate table stu_tb; -- 删除表,再建一个相同结构的表
show tables;
desc stu_tb;
drop table if exists stu_tb; -- 删除表
show tables;
不总结=白学
THE END