库的增删改查
-
增
-- 创建库
create database 库名 charset 字符编码;
-
删
-- 删除库
drop database 库名;
-
改
-- 修改字符编码
alter database 库名 charset 字符编码;
# 注:一般只改字符编码,数据库名称是不能改的
-
查
-- 查询当前账户下所有的库
show databases;-- 查询指定库
show create database 库名;
-
例
-- 登录数据
mysql -uroot -p -P3306 -h127.0.0.1-- 查看所有库
show databases;-- 查看某个库
show create database test;-- 创建库
create database test;-- 创建库指定编码
create database test charset utf8;-- 修改库编码
alter database test charset gbk;-- 删除库
drop database test;
表的增删改查
-
增
-- 新增表
create table 表名(字段名1 类型(宽度) 约束条件,字段名2 类型(宽度) 约束条件,字段名3 类型(宽度) 约束条件);
-- 注:
-- 1、字段名不能重复;
-- 2、宽度和约束条件可选;
-- 3、字段名和类型是必须的。
-
删
-- 删除表
drop table 表名
-
改
-- 修改表名
alter table 表名 rename 新表名;-- 修改字段名、数据类型及约束条件
alter table 表名 change 旧字段名 新字段名 数据类型 约束条件;-- 新增字段
alter table 表名 add 字段名 数据类型 约束条件;-- 可指定新增字段位置
alter table 表名 add 字段名 数据类型 约束条件 first/after 某个字段;
-
查
-- 查看某个数据库下面的所有表
Show tables;-- 查看某个表结构
Show create table 表名(\G);-- 查看表【Desc & describe】
desc 表名;
-
例
-- 切换库,创建表之前要指定在哪个库
use test;
-- 创建表
create table test_tb(name char(10) not null, sex char(1) not null, age int);-- 查看某个表
show create table test_tb;
desc test_tb;-- 查看当前库下所有的表
show tables;-- 修改表
-- 修改表字段 数据类型 约束条件
alter table test_tb change name name1 varchar(10) not null;-- 新增表字段
alter table test_tb add addr char(20), add addr2 char(20);-- 指定位置新增
alter table test_tb add id int first;
alter table test_tb add addr3 varchar(10) after name1;-- 删除表字段
alter table test_tb drop addr3;-- 删除表
drop table test_tb;
来自: 学习MySQL(二):库表的操作