TCL:事务控制语言
事务:一个或者一组sql语句组成的一个执行单元,这个执行单元,要么都执行要么都不执行
案例;转账
张三丰 1000
郭襄 1000
场景,张三丰给郭襄转账500块钱
update 表 set 张三丰的余额=500 where name='张三丰';
update 表 set 郭襄的余额=1500 where name='郭襄';
事务的特性ACID 这是必须要记住的
show ENGINES
事务的创建:
隐式事务:事务没有明显的开启或者结束的标记
比如,之前学习过的insert update delete语句
显式事务;事务具有明显的开启或者结束的标记,前提是先设置自动提交功能为禁用
show VARIABLES like 'autocommit';--显示的是on 表示的是开启自动提交
set autocommit=0;表示将自动提交关闭掉了
事务的语法:
步骤1:开启事务
set autocommit=0;
start TRANSACTION;可选的
步骤2:编写事务中的sql语句(select insert update delete)
语句1
语句2
.。。
步骤3:结束事务
commit 提交事务
rollback:回滚事务
案例;模拟转账
create TABLE if not EXISTS account(
id int,
username varchar(20),
balance DOUBLE(10,2)
)
insert into account VALUES(1,'张无忌',1000);
insert into account VALUES(1,'赵敏',1000);
select * from account;
#开启事务
set autocommit=0;
start TRANSACTION;
#编写一组事务的语句
update account set balance =1000 where username='张无忌';
update account set balance =1000 where username='赵敏';
#结束事务
#commit;
ROLLBACK;
SAVEPOINT:设置保存点 只能够搭配rollback使用
set autocommit=0;
start TRANSACTION;
#编写一组事务的语句
update account set balance=3000 where username='张无忌';
SAVEPOINT a;
update account set balance =20000 where username='赵敏';
#结束事务
#commit;
ROLLBACK to a;
select * from account;