数据库
存储数据对象的容器
数据对象:表 、视图、触发器、存储过程、事件等。
注当一个命令既能操作数据库又能操作表的时候要 加上操作对象 数据库 + database 表 +table(create database db_name ; create table tb_name)
对数据库操作(不区分大小写,中括号中可选)
创建数据库
create database 或者 create schema
create database [if not exists] test1;
选择数据库
use db_name;
use test1;
修改数据库
alter database test1 default character set gb2312 ;(设置默认字符集)
删除数据库
drop database [if exists] db_name;
对表的操作
创建表(列用 逗号隔开)
create table students(
id int not null auto_increment,
学号 char(6) not null primary key,
姓名 char(8) not null,
性别 tinyit(1) not null default 1,
备注 text null);
注:primary key 设为主键、auto_increment 自增长、default 默认值
注:自增长属性只能为 整型列,每个表只能有一个自增长列,并且必须被索引。
索引
先解释一下索引:
索引是根据表中的 一列或者若干列按照一定的顺序建立的列值与记录行之间的对应关系表。
简而言之:就是当查询一个表中的一行数据的时候,不再遍历原表中的所用数据,而是查找索引表根据索引表对应的对应关系可以找到原表的一行数据。大大减少了查询时间。(Java中HashMap 的设计也是根据这个原理 。查找键 而返回值)
复制表
当表有很多重复列不必要在去敲一遍;
like 关键字 创建一个与原表想用结构的新表。(除了类容,其他的例如 索引,主键等 都将复制)相当于再次执行了建表语句。
as 关键字可以复制表的类容,但是索引 和完整性约束不会复制
create table new_table like old_table;
create talbe copy_table as old_table;
修改表结构
开发中多用可视化工具这里就直接举个例子不做赘述。
新增一列
alter table t1 add column a tinyint null;
改列名
alter table t1 change a b integer;
修改指定列类型
alter table t1 modify b bigint not null;
修改表名
alter table a rename to b;
或者
rename table t1 to t2, t3 to t4;
删除表
drop table if exists tb_name;
对表记录的操作
插入新的记录
insert into tb_name(要插入哪几列, 不写默认为全部列) values(对应列的值 顺序不能错)
如果插入主键 唯一性约束的列不能有重复,如果重复将失败 使用替换可以
替换旧记录
replace into tb_name values();
修改记录
updata tb_name set column_name=new_column where 条件
删除记录
delete from tb_name where 条件
Select语句
可以实现对表的选择、投影及其连接操作
指定列
select column1,column2 from tb_name;
select * from tb_name; (全部列)定义列别名
select column_name as “column_alias” from tb_name where 条件;
(注:别名中有空格时要用引号,where 中不能使用别名)
- 替换查询结果中的数据
不是数据库中数据是结果的数据
select 学号 ,姓名,
//--------------------------------------
case
when 总成绩 is null then '缺考'
when 总成绩 <50 then '不及格'
when 总成绩 >=50 and 总成绩 <=52 then '合格'
else '优秀'
end
//这里就相当于一个列值的显示规则
//--------------------------------------
as 等级 //给这个列 一个别名
from tb_name where 条件
取消结果集中的重复行
select distinct *from tb_name;
- 聚合函数
select count(*) as 行数 from tb_name ;
(只用一行不是全null 这一行就有效)
select count(column_name) from tb_name ;
column_name不为空的个数
- 匹配模式
select column1,column2 from tb_name where name like ‘王%’
% 多个占位符 _一个占位符
使用正则表达式
where name regexp ‘^李’- 范围
select *from tb_name where name in(‘zhang’,‘li’);
in 表示在 括号里面的范围之类的 所以括号里面可以在写 select 语句
不过选择的列要和in 前面的列一致.事件
和程序中事件差不多 有触发条件 即可触发
存储过程
delimiter$$ //定义存储过程的结束符号
create procedure name (in bl_name char(6),out outname int)
//in 调用该存储过程时要传入的参数 out 为该存储过程输出的结果
begin
declare a1 ,a2 int ;//定义变量
select column into a1 from tb_name where id= bl_name ;
if a1 ==1 then
set outname=1;
end $$
delimiter ; 恢复 结束符号为 ; 因为 存储过程中有 ; 所以不能读到; 就结束所以重新定义了结束符号
调用
call name(“121”,@res) 定义一个变量 res 用来存放返回结果
select @res 可以看到结果
触发器
create trigger delete_tr after deleted on tb_name for each row
delete from sa
事物
一般在代码中实现
1.原子性
2.一致性
3.隔离性
4.持久性