目录
点睛
要么都成功,要么都失败。
ACID原则:保证数据的安全。
事务编程一般步骤
1 开启事务
2 事务提交 commit
3 事务回滚 rollback
4 关闭事务
需求
实现一个转账需求
A:1000
B:1000
实现A向B转账100元。
Junit单元测试
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
数据库
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`money` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into account(id,name,money) values(1,'A',1000);
insert into account(id,name,money) values(2,'B',1000);
代码
package com.cakin;
import org.junit.Test;
import java.sql.*;
/**
* @ClassName: JdbcTest3
* @Description: jdbc事务:实现转账
* @Date: 2020/6/19
* @Author: cakin
*/
public class JdbcTest3 {
@Test
public void test() {
// useUnicode=true&characterEncoding=utf8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8";
String username = "root";
String password = "123456";
Connection connection = null;
try {
// 1 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2 获得连接对象
connection = DriverManager.getConnection(url, username, password);
// 3 开启事务
connection.setAutoCommit(false);
// 4 编写SQL
String sql1 = "update account set money = money-100 where name = 'A'";
connection.prepareStatement(sql1).executeUpdate();
// 制造错误
// int i = 1 / 0;
String sql2 = "update account set money = money+100 where name = 'B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
} finally {
// 6 关闭资源
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
来源:oschina
链接:https://my.oschina.net/u/4348626/blog/4317751