目录
一、注意事项
1.操作表的前提是已经创建库并使用
2.表名如果是关键字需要用反引号引起来!!!
3.数据类型:
字符串类型: varchar(字符长度)
整数类型: int 注意: 默认长度是11,如果int不够用就用bigint
浮点类型: float(python默认) 或者 double(java默认) decimal(默认是有效位数是10,小数后位数是0)
日期时间: date datetime year
二、创建表
先创建库:create database if not exists day01_db;(if not exists在上一个博客已经介绍过,可以不写)
使用库:use day01_db;
创建表:(字段类型后面还有个约束,写不写都可以,这里先不写,后面学了约束再进行介绍)
create table 表名(字段1 字段1类型 [字段1约束],字段2 字段2类型 [字段2约束]....);
注意:若表名已经存在会报错:表已存在不能再创建
create table if not exists 表名(字段1 字段1类型 [字段1约束],字段2 字段2类型 [字段2约束]....);
注意:若表名不存在自动创建库,若表名存在则忽略,if not exists可以不写
create table if not exists 表名(字段1 字段1类型 [字段1约束],字段2 字段2类型 [字段2约束]....)character set utf8;
注意:设置编码为utf8,DdtaGrip软件默认是utf8,可以不写。
三、删除表
drop table 表名; 注意:若表名不存在会报错:表不存在,无法删除
drop table if exists 表名; 注意:若表名不存在会报错:表不存在,无法删除 if exists可以不写
四、修改表
1.修改表名:rename table 旧表名 to 新表名;
2.修改表中字段:
添加字段:alter table 表名 add 字段名 字段类型 [字段约束];
删除字段:alter table 表名 drop 字段名;
修改字段:alter table 表名 change 旧字段名 新字段名 新字段类型;
注意:不管只修改字段名还是字段类型或者都修改,都需要写旧字段名,新字段名(不改就写旧字段名)和新字段类型(不改就写旧字段类型)
查看字段:desc 表名;
五、查询表
查看所有表:show tables;
查看字段信息:desc 表名;
查看建表语句:show create table 表名;
六、完整代码
/*
操作表的前提是得先创建库
*/
#创建库
create database day01_db;
create database if not exists day01_db;
#使用库
use day01_db;
#创建表
create table student
(
id int,
name varchar(100),
age int,
height float,
birthday date
);
create table if not exists test1
(
id int
);
#查看所有表
show tables;
#删除表
drop table test1;
drop table if exists test1;
#修改表名
rename table student to stu;
create table if not exists stu
(
id int,
name varchar(100),
age int,
height float,
birthday date
);
##查看建表语句:show create table 库名;
/*
1.表名字段名自动加了反引号,关键字会被忽略
2.int加了默认11个字符
3.所有字段值都设置了默认值null
4.如果是字符串类型,还设置了默认编码为utf8
5.默认选择了存储引擎,有的版本默认myisam,有的版本默认innodb
6.整个表设置了默认编码
*/
show create table stu;
#表中字段增删改查,本质都在修改表
#添加字段
alter table stu add weight double;
# 注意:如果字段名是关键字,需要用反引号引起来
alter table stu add `desc` double;
#删除字段
alter table stu drop weight;
alter table stu drop `desc`;
#修改字段
alter table stu change birthday bir datetime;
# 注意:modify只能改类型,所以记change即可
#查看字段信息
desc stu;