手动开启事务
事务默认提交被开启(@@autocommit=1)后,此时不能使用事务回滚,但我们可手动开启一个事务处理事件,这样就可以发生回滚。
使用begin 或者star transaction 手动开启一个事务
begin;
update user set money=money-100 where name='a';
update user set money=money+100 where
name='b';
由于手动开启事务没开启自动提交
此时发生变化的数据仍然是保存在一个临时数据表中;
select * from user;
+----+------+-------+
| id | name | money |
+----+------+-------+
| 1 | a | 900 |
| 2 | b | 1100 |
+----+------+-------+
测试回滚
rollback;
select * from user;
+----+------+-------+
| id | name | money |
+----+------+-------+
| 1 | a | 1000 |
| 2 | b | 1000 |
+----+------+-------+
仍然用commit提交数据,提交后无法再发生本次事务的回滚。
begin;
update user set money=money-100 where name='a';
update user set money=money+100 where name='b';
select * from user;
+----+------+-------+
| id | name | money |
+----+------+-------+
| 1 | a | 900 |
| 2 | b | 1100 |
+----+------+-------+
提交数据
commit;
测试回滚(无效,因为表的数据已经被提交)
rollback;
事务的 ACID 特征与使用
事务四大特征
A 原子性:要求事务是最小单位不可再分割;
C 一致性:要求同一事务中的sql语句,必须保证同时成功或者失败;
I隔离性:事务1 和 事务2 之间是具有隔离性的;
D持久性:事务一旦结束(commit),就不能再返回(rollback)。
本文详细介绍了如何在数据库中手动开启事务,包括使用begin或start transaction命令启动事务,以及如何通过commit提交更改或使用rollback撤销事务。此外,还深入探讨了事务的四大特性:原子性、一致性、隔离性和持久性。
1529

被折叠的 条评论
为什么被折叠?



