Mysql默认是autocommit=1,也就是说默认是立即提交,如果想开启事务,先设置autocommit=0
set @@autocommit = 0;
select @@autocommit;
开启事务:START TRANSACTION;或者begin;
提交事务:commit
回滚事务:rollback
部分事务
savepoint保存点是部分事务,是原事务的一部分。
drop table t;
create table t(a int, primary key(a));
begin;
insert into t(a) values(1);
SAVEPOINT s;
insert into t(a) values(2);
ROLLBACK to SAVEPOINT s;
commit;
表中只有1个元素,值是1
嵌套事务
当执行一个START TRANSACTION指令时,会隐式的执行一个commit操作,就是开启新事务时,自动提交原来的旧事务
所以没办法开启两个事务,只能通过savepoint来实现嵌套事务
drop table t;
create table t(a int, primary key(a));
begin;
insert into t(a) values(1);
SAVEPOINT s;
insert into t(a) values(2);
insert into t(a) values(2);
ROLLBACK to SAVEPOINT s;
commit;
因为异常,事务回滚,保存点的异常向上传播到主事务,主事务也回滚
表中没有元素
drop table t;
create table t(a int, primary key(a));
begin;
insert into t(a) values(1);
insert into t(a) values(1);
SAVEPOINT s;
insert into t(a) values(2);
ROLLBACK to SAVEPOINT s;
commit;
主事务异常,直接回滚,第二个事务就不执行
表中没有数据