Database views, triggers, transactions, stored procedures, functions, backup and recovery

Advanced section

1. View

What is the view,

Is essentially a virtual table, that is visible but does not actually exist

Why do we need virtual table ????

scenes to be used

scene 1:

We hope that some part of the query can only view records in a table, you can use the View

Scenario 2:

Simplify sql statement written

Instructions:

语法:
create [or replace] view view_name as 查询语句;
or replace 如果视图已经存在了 就替换里面的查询语句;

# 修改视图
alter view view_name  as 新的语句;

# 删除视图
drop view  view_name;

# 查看
desc view_name;
show create view view_name;



# 限制可以查看的记录 
create table salarys(id int,name char(10),money float);
insert into salarys values(1,"张三丰",50000),(2,"张无忌",40000);
# 创建视图  限制只能查看张无忌的工资
create view zwj_view as select *from salarys where name = "张无忌";

# 简化sql编写
create table student(
  s_id int(3),
  name varchar(20), 
  math float,
  chinese float 
);
insert into student values(1,'tom',80,70),(2,'jack',80,80),(3,'rose',60,75);

create table stu_info(
  s_id int(3),
  class varchar(50),
  addr varchar(100)
);
insert into stu_info values(1,'二班','安徽'),(2,'二班','湖南'),(3,'三班','黑龙江');
# 查询班级和学员的对应关系做成一个视图  方便后续的查询 
create view class_info as select student.s_id,name,class from student join stu_info on student.s_id = stu_info.s_id;

select *from class_info;

Note: Modify the view can also cause changes in the original table, we do not do this, view only for queries

2. Trigger

Triggers, sql statement period is associated with a table, it will at some point in time to meet a condition triggered automatically after execution

The two key factors:

Time

Before the event occurs before | after the incident after

Event

​ update delete insert

Then automatically trigger comprises two objects

old update, delete available

new update, insert available

Used to do:

Can be used: when the data table is modified, automatically recording some data, perform some sql statement

Syntax:

create trigger t_name  t_time t_event on  table_name for each row 
begin
#sql语句。。。。。:
end

Case:

#准备数据
CREATE TABLE cmd (
    id INT PRIMARY KEY auto_increment,
    USER CHAR (32),
    priv CHAR (10),
    cmd CHAR (64),
    sub_time datetime, #提交时间
    success enum ('yes', 'no') #0代表执行失败
);
#错误日志表
CREATE TABLE errlog (
    id INT PRIMARY KEY auto_increment,
    err_cmd CHAR (64),
    err_time datetime
);

#需求: 当插入cmd表 的时候 如果执行状态时失败的 那么将信息插入到errlog中

# 将结束符设置为|
delimiter |
create trigger cmd_insert after insert on cmd for each row
begin
if new.success = "no" then
    insert into errlog values(null,new.cmd,new.sub_time);
end if;
end|
# 在还原之前的结束符 
delimiter ;


# 创建一个触发器 叫cmd_insert  
# 触发器会在 插入数据到cmd表后执行 
# 当插入的记录的success为no时 自动插入记录到errlog中 


# 错误原因 遇到分号自动提交了  , 需要重定义  行结束符  
delimiter |

# 删除触发器
drop trigger cmd_insert;

#查看 所有触发器
show triggers;

# 查看某个触发器的语句 
show create trigger t_name;

3. Transaction very important

What is a transaction

The transaction is a combination of a series of sql statements, as a whole

Transaction features:

Atomic, refers to this transaction sql statement as a whole, it can not be split, either perform or all fail

Consistency, after the end of transaction execution, the associated table must be correct, it does not send data confusion

Isolation, isolation between transactions, data not affect each other, even if the operation of the same table, essentially lock The lock granularity is divided into several different isolation levels

Persistent, after the successful implementation of transaction data will be stored permanently, can not be restored

Scenarios transactions:

Operation 1. The transfer account of the forwarding minus 2. Transferred to the balance of the account do increase the operating

​ money(name,money)

​ update money set money = money - 100 where name = "李寻欢";

​ update money set money = money + 100 where name = "步惊云";

Note: mysql client cmd in the official at the end of a transaction is the default on open, will be a sql statement as a transaction is automatically submitted

grammar:

#开启事务 
start transaction 
#sql 语句......
#sql 语句......
rollback  #回滚操作   即撤销没有提交之前的所有操作 
#sql 语句......
commit  #提交事务 一旦提交就持久化了


CREATE TABLE `account` (
  `name` char(10),
  `money` float  
);

start transaction;
update account set money = money - 100 where name = "一只穿云箭";
update account set money = money + 100 where name = "千军万马";
commit;


# 何时应该回滚  当一个事务执行过程中出现了异常时
# 何时提交   当事务中所有语句都执行成功时

# 保存点 可以在rollback指定回滚到某一个savepoint ,也就是回滚一部分  

start transaction;
update account set money = money - 100 where name = "一只穿云箭";
savepoint a;
update account set money = money - 100 where name = "一只穿云箭";
savepoint b;
update account set money = money - 100 where name = "一只穿云箭";
savepoint c;

select * from account;

# 回滚至某个保存点 
rollback to 保存点名称

read committed

Magic Reading is because others insertion and deletion in

Repeatability is not because people do than update

Modify the isolation level:

修改全局的  
 set global transaction isolation level read committed;
 或者:
 set @@tx_isolation = "asasasasas-read";
 修改局部
 set session transaction isolation level read committed;
 

 @@系统内置变量
 @表示用户自定义的变量

4. Stored Procedures priority control

What is a stored procedure,

Any combination sql statement, are placed one stored procedure, a function similar to, a function, there are parameters, or the function body

Used to do:

Which can contain any sql statement, logic processing, transaction processing, all we have learned sql statement can be put inside

Three data handling

1. The application only concerned with the business logic, all the data associated with the logic package into mysql

Advantages: application to be processed matter becomes less, you can reduce network traffic

Disadvantages: increased labor costs, communication costs, reduce overall development efficiency

2. The application is necessary to deal with business logic, but also to write your own sql statement

Benefits: reduce communication costs, labor costs

Disadvantages: increased network transmission, write sql statement is very tedious, error-prone

3. sql statement automatically generated and executed by the object-relational mapping ORM framework

Advantages: sql statement does not need to be in writing, and significantly enhance the speed of development

Disadvantages: not flexible enough, application developers and database completely isolated, can lead to only focus on the development of the upper layer, but do not know the underlying principle

Using stored procedures

Syntax:

create procedure p_name(p_type p_name p_date_type)
begin
sql.......
end


p_type 参数的类型  in输入  out输出   inout即可输出也可输入
p_name 参数的名字 
p_data_type 参数的数据类型 如  int float

#注意:out参数必须是一个变量 不能是值

#案例:
delimiter |
create procedure add1(in a float,in b float,out c float)
begin 
set c = a + b;
end|
delimiter;

#调用
set  @res = 0;
call add1(100,10,@res);

# 删除
drop procedure 名称;

# 查看
show create procedure 名称;

# 查看全部  db02库下的所有过程
select name from mysql.proc where db = 'day41' and type = 'PROCEDURE';


delimiter |
create procedure transfer2(in aid int,in bid int,in m float,out res int)
begin 
    declare exit handler for sqlexception
    begin
        # 异常处理代码
        set res = 99;
        rollback;
    end;
    
    start transaction;
    update account set money = money - m where id = aid;
    update account set money = moneys + m where id = bid;
    commit;
    set res = 1;
end|
delimiter ;

5. Functions

Custom Functions

create function func_name(参数 类型)
函数体
returns 返回值的类
return 返回值 


delimiter | 
create function add2(a int,b int)
returns int
return a + b|
delimiter ;


#查看创建语句 
show create function name;

#查看所有函数的状态
show function status;

#查看某个库下所有函数
select name from mysql.proc where db = "库名称" and type = "FUNCTION";

# 删除
drop function name;

6. Backup and Recovery

# 备份
mysqldump.exe   
mysqldump -u用户名 -p密码 数据库 表名1 表名2 .... > 文件路径....
# 注意 第一个表示数据库  后面全都是表名
mysqldump -uroot -p day41 student  > 


#备份多个数据库
mysqldump -uroot -p111 --databases day41 day40  > x3x.sql
#指定 --databases 后导出的文件包含 创建库的语句   而上面的方式不包含

#备份所有数据  
mysqldump -uroot -p111 --all-databases > all.sql


#自动备份
linux crontab 指令可以定时执行某一个指令



# 恢复数据:
没有登录mysql 
mysql < 文件的路径


已经登录了MySQL 
source  文件路径


注意: 如果导出的sql中没有包含选择数据库的语句 需要手动加上 

7. Process Control

delimiter | 
create procedure showjishu()
begin
declare i int default 0;
aloop: loop
set i = i + 1;
if i >= 101 then leave aloop; end if;
if i % 2 = 0 then iterate aloop; end if;
select i;
end loop aloop;
end|
delimiter ;

Regular match

语法:
select  *from  table where 字段名  regexp "表达式!";

create table info(name char(20));
insert into  info values("jack sbaro"),("jack rose"),("jerry sbaro"),("sbaro jerry"),("jerry");

# 注意: 不能使用类似 \w 这样的符号   需要找其他符号来代替  

Guess you like

Origin www.cnblogs.com/zhoajiahao/p/11203766.html