“JDBC数据库事务”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第44行: | 第44行: | ||
INSERT INTO `user_table` VALUES ('AA','123456',1000),('BB','654321',1000); | INSERT INTO `user_table` VALUES ('AA','123456',1000),('BB','654321',1000); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | |||
+ | ==== 模拟经典的转账业务场景 ==== | ||
+ | <syntaxhighlight lang="java"> | ||
+ | /** | ||
+ | * 针对于数据表 user_table 来说: | ||
+ | * AA用户给BB用户转账100 | ||
+ | * | ||
+ | * update user_table set balance = balance - 100 where user = 'AA'; | ||
+ | * update user_table set balance = balance + 100 where user = 'BB'; | ||
+ | */ | ||
+ | @Test | ||
+ | public void testUpdate() { | ||
+ | String sql1 = "update user_table set balance = balance - 100 where user = ?"; | ||
+ | update(sql1, "AA"); | ||
+ | |||
+ | //模拟网络异常 | ||
+ | System.out.println(1 / 0); | ||
+ | |||
+ | String sql2 = "update user_table set balance = balance + 100 where user = ?"; | ||
+ | update(sql2, "BB"); | ||
+ | System.out.println("转账成功"); | ||
+ | } | ||
+ | </syntaxhighlight>扣钱的操作执行成功,加钱的操作未执行。 |
2023年1月3日 (二) 22:14的版本
https://www.bilibili.com/video/BV1eJ411c7rf/?p=34
11:57之前是数据库连接及 PreparedStatement 使用小结
数据库事务介绍
- 事务:一组逻辑操作单元,使数据从一种状态变换到另一种状态
- 事务处理(事务操作):保证所有事务都作为一个工作单元来执行,即使出现了故障,都不能改变这种这行方式。当在一个事务中执行多个操作时,要么所有的事务都被提交(commit),那么这些修改就永久地保存下来;要么数据库管理系统将放弃所作的所有修改,整个事务回滚(rollback)到最初状态。
- 为确保数据库中数据的一致性,数据的操纵应当是离散的成组的逻辑单元:当它全部完成时,数据的一致性可以保持,而当这个单元中的一部分操作失败,整个事务应全部视为错误,所有从起始点以后的操作应全部回退到开始状态。
JDBC事务处理
- 数据一旦提交,就不可回滚。
- 数据什么时候意味着提交?
- 当一个连接对象被创建时,默认情况下是自动提交:每次执行一个 SQL 语句时,如果执行成功,就会向数据库自动提交,而不能回滚。
- 关闭数据库连接,数据就会自动的提交。如果多个操作,每个操作使用的是自己单独的连接,则无法保证事务。即同一个事务的多个操作必须在同一个连接下。
- JDBC 程序中为了让多个 SQL 语句作为一个事务执行:
- 调用 Connection 对象的 setAutoCommit(false); 以取消自动提交事务
- 在所有的 SQL 语句都成功执行后,调用 commit(); 方法提交事务
- 在出现异常时,调用 rollback(); 方法回滚事务
https://www.bilibili.com/video/BV1eJ411c7rf/?p=35
数据库事务的问题的引入
数据库准备
CREATE TABLE `user_table` (
`user` varchar(20) NOT NULL,
`password` varchar(45) DEFAULT NULL,
`balance` int(11) DEFAULT NULL,
PRIMARY KEY (`user`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `user_table` VALUES ('AA','123456',1000),('BB','654321',1000);
模拟经典的转账业务场景
/**
* 针对于数据表 user_table 来说:
* AA用户给BB用户转账100
*
* update user_table set balance = balance - 100 where user = 'AA';
* update user_table set balance = balance + 100 where user = 'BB';
*/
@Test
public void testUpdate() {
String sql1 = "update user_table set balance = balance - 100 where user = ?";
update(sql1, "AA");
//模拟网络异常
System.out.println(1 / 0);
String sql2 = "update user_table set balance = balance + 100 where user = ?";
update(sql2, "BB");
System.out.println("转账成功");
}
扣钱的操作执行成功,加钱的操作未执行。