目录
1.
查询所有数据库
show databases;
2. 创建数据库
create database 数据库名;
指定字符集格式:
create database 数据库名 character set utf8/gbk;
举例:
create database db1;
create database db2 character set utf8;
create database db3 character set gbk;
3.
查询数据库详情
show create database 数据库名;
4. 删除数据库
drop database 数据库名;
5. 使用数据库
操作表和数据之前必须先使用某个数据库,否则会报错
use 数据库名;
表相关的SQL
1.
创建表
create table 表名(字段1名 类型,字段2名 类型);
指定字符集格式:
create table 表名(字段1名 类型,字段2名 类型) charset=utf8/gbk;
举例:
create table person(name varchar(20),age int);
create table student(name varchar(10))charset=utf8;
create table car(name varchar(20),price int)charset=gbk;
2. 查询所有表
show tables;
3. 查询表详情
show create table 表名;
4.
查询表字段信息
desc 表名;
5. 删除表
drop table 表名;
6. 修改表名
rename table 原名 to 新名;
7. 添加表字段
- 最后面添加格式:
alter table 表名 add 字段名 类型;
- 最前面添加格式:
alter table 表名 add 字段名 类型 first;
- xxx字段后面添加格式:
alter table 表名 add 字段名 类型 after 字段名;
举例:
alter table emp add age int; //最后面
alter table emp add id int first; //最前面
alter table emp add salary int after name; //名字后面添加2. 删除表字段
8.删除表字段
alter table 表名 drop 字段名;
9. 修改表字段
alter table 表名 change 原名 新名 新类型;
Version:0.9 StartHTML:0000000105 EndHTML:0000000461 StartFragment:0000000141 EndFragment:0000000421
数据相关SQL
1. 插入数据
- 全表插入格式:
insert into 表名 values(值1,值2);
- 指定字段插入格式:
insert into 表名(字段1名,字段2名)values (值1,值2);
- 批量插入格式:
insert into 表名 values(值1,值2),(值1,值2),(值1,值2);
举例:
insert into person values("Tom",18); //全表
insert into person(name) values('Jerry'); //指定字段
insert into person values("aaa",10),("bbb",20), ("ccc",30);
- 中文问题:
insert into person values("刘德华",20);
如果执行上面的代码报以下错误, 执行set names gbk; 重新插入即可
2. 查询数据
举例:
select name from person; //查询所有姓名
select name,age from person; //查询所有姓名和年龄
select * from person; //等效上面
select * from person where age>20; //查询年龄大于20的信息
select age from person where name='刘德华';//查询刘德华的年龄
3.
修改数据
update 表名 set 字段名=值,字段名=值 where 条件;
举例:
update person set name="杰瑞" where name='Jerry';
update person set age=88 where name='Tom';
update person set name='张学友',age=50 where name='刘德华';
update person set age=10 where age<50;
update person set name='Lucy' where age is null; //null不能用=判断需要使用 is
4. 删除数据格式:
delete from 表名 where 条件;
举例:
delete from person where name='Lucy';
delete from person where age=50;
delete from person; //删除所有
数据类型
整数:
int(m)和bigint(m), bigint等效java中的long, m 代表显示长度(m是用来补零的) 补零需要结合zerofill 关键字
create database dbday2 character set utf8;
use dbday2;
create table t1(name varchar(20),age int(10) zerofill);
insert into t1 values('aaa',18);
select * from t1;
2. 浮点数:
double(m,d) m代表总长度 d代表小数长度 (23.534 m=5 d=3), 超过精度浮点数decimal(m,d) 精度远高于double 只有涉及到超高精度运算时使用.
3. 字符串
- char(m):m代表字符长度, 固定长度字符串, m=10 存abc 占10, 执行更高效, 如果保存的内容长度固定 时使用char 否则使用varchar, 最大长度255
- varchar(m):可变长度字符串, m=10 存abc 占3 , 更节省空间, 最大长度65535但是建议保存255以内长 度的数据
- text(m):可变长度字符串,最大长度65535, 建议保存长度大于255的内容
4. 日期:
-
date:只能保存年月日
- time:只能保存时分秒
- datetime:保存年月日时分秒, 默认值为null, 最大值 9999-12-31