1. 表的基础操作
需要操作数据库中的表时,需要先使用该数据库
use db_test;
1.1 查看表结构
desc 表名;
1.2 创建表
- 基本语法:
CREATE TABLE table_name (
field1 datatype,
field2 datatype,
field3 datatype
);
- 代码示例:
可以使用comment增加字段说明
create table stu_test (
id int,
name varchar(20) comment '姓名',
password varchar(50) comment '密码',
age int,
sex varchar(1),
birthday timestamp,
amout decimal(13,2),
resume text
);
1.3 删除表
- 基本语法:
DROP TABLE table_name;
- 代码示例:
-- 删除 stu_test 表
drop table stu_test;
-- 如果存在 stu_test 表,则删除 stu_test 表
drop table if exists stu_test;
2. 新增(Create)
- 基本语法:
INSERT table_name VALUES (value);
- 案例分析:
-- 创建一张学生表
DROP TABLE IF EXISTS student;
CREATE TABLE student (
id INT,
sn INT comment '学号',
name VARCHAR(20) comment '姓名',
qq_mail VARCHAR(20) comment 'QQ邮箱'
);
2.1 单行数据 + 全列插入
-- 插入两条记录,value_list 数量必须和定义表的列的数量及顺序一致
INSERT INTO student VALUES (100, 10000, '唐三藏', NULL);
INSERT INTO student VALUES (101, 10001, '孙悟空', '11111');
2.2 多行数据 + 指定列插入
-- 插入两条记录,value_list 数量必须和指定列数量及顺序一致
INSERT INTO student (id, sn, name)<