
文章目录
前言
DDL 操作是与数据库结构相关的操作,它们不涉及实际的数据操作,而是用于管理数据库的结构和元数据。今天我将为大家分享关于MySQL数据库的DDL操作。
数据库操作
SQL | 功能 |
---|---|
show databases; | 查看所有的数据库 |
create database [if not exists] 数据库名 [charset/character=utf8]; | 创建数据库 |
use 数据库名; | 选中数据库 |
drop database 数据库名; | 删除数据库 |
alter database 数据库名 character set 编码; | 修改数据库编码 |
查看已存在的所有数据库
show databases
会将当前MySQL下的所有数据库给展示出来。其中 information_schema
mysql
performance_schema
sys
是MySQL默认具有的数据库。

创建数据库
SQL这样创建数据库 create database 数据库名 (character set)/charset 编码格式;
sql
create database test character set utf8;
show databases;

选中数据库
后面的表操作都需要先指定操作的是哪一个数据库,我们使用 use 数据库名
来选中数据库。这里我们讲到表操作的时候会为大家展示用法。
删除数据库
当我们需要删除某一个数据库的时候,使用 drop database 数据库名
来删除指定数据库。
sql
drop database test;
show databases;

修改数据库编码
如果我们在创建数据库之后还想要修改数据库编码的时候就使用 alter database 数据库名 character set 编码
来进行操作。

sql
alter database mydb1 character set GB2312;

表操作
表位于对应的数据库中,所以我们进行表操作的时候,必须使用 use 数据库名
来指定操作的是哪个数据库。
MySQL基础表操作
SQL语句 | 功能 |
---|---|
create table 表名 (列名1 该列数据类型,列名2 该列数据类型); | 创建表,同时指定列的数据类型 |
show tables; | 显示该数据库下的所有表 |
show create table 表名; | 显示该表的创建语句 |
desc 表名; | 显示该表的结构 |
drop table 表名; | 删除指定表 |
创建表
在创建表之前我们需要知道 MySQL 有哪些数据类型。
MySQL基本数据类型
当知道有什么数据类型的之后,我们就可以来创建表了。
sql
use mydb1;
create table student(id int,name varchar(20));
show tables;

显示创建表时的语句
sql
show create table student;

显示表结构
sql
desc 表名;
sql
desc student;

删除表
sql
drop table 表名;
sql
drop table student;
show tables;

修改表的结构
修改表的结构需要运用到 alter table 表名 操作
增加列
alter table 表名 add 列名 该列数据类型;
sql
alter table student add gender varchar(10);
desc student;

修改列
alter table 表名 change 旧列名 新列名 新列数据类型;
sql
alter table student change gender tel int;
desc student;

删除列
alter table 表名 drop 列名
sql
alter table student drop tel;
desc student;

修改表名
rename table 表名 to 新表名;
sql
rename table student to stu;
show tables;
