数据库中的数据是存储在基本表中的,所以需要先创建数据表再添加数据。
创建表的同时指定表名、字段名以及每个字段的数据类型和约束条件。
create table <表名>(
<字段名1> <数据类型1>[ <约束条件1>,
<字段名2> <数据类型2> <约束条件2>,
...
<字段名n> <数据类型n> <约束条件n>]
);
<表名>:表名不可与SQL关键字相同,同一个数据库中的表名不可重复。
<字段名>:字段名不可与SQL关键字相同,同一个表中的字段名不可重复。
<约束条件>:约束条件可以不指定。
示例:
-- 学生表
create table stu (
s_id int,
s_name varchar(10),
s_birth date,
s_sex varchar(10)
);
在当前数据库中可以查看创建好的数据表。
show tables [like '表名'];
示例:查看当前数据库内的所有表
show tables;
创建好数据表之后,可以查看表结构。
describe <表名>; 或 desc <表名>;
示例:查看stu表的结构定义
desc stu;
+--------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------+------+-----+---------+-------+
| e_id | varchar(5) | YES | | NULL | |
| e_name | char(5) | YES | | NULL | |
| e_age | int(11) | YES | | NULL | |
| d_id | varchar(5) | YES | | NULL | |
+--------+------------+------+-----+---------+-------+
Null:表示该字段是否可以存储 NULL 值。 Key:表示该字段是否已编制索引。PRI 表示主键,UNI 表示 UNIQUE 唯一索引,MUL 表示某个给定值允许出现多次。 Default:表示该字段是否有默认值,如果有,值是什么。 Extra:表示可以获取的附加信息,如 AUTO_INCREMENT 等。
删除表指删除表结构的同时删除表中数据,因此需谨慎使用。
drop table [if exists] <表名> [,<表名1>,<表名2>,...<表名n>];
可删除多张表,if exists避免表不存在时报错。
示例:删除stu表
drop table stu;
这时,我们再执行下面代码查看数据库中还有哪些表
show tables;