JDBC事务处理
事务:一个包含多个步骤的业务操作。如果这个业务被事务管理,要么同时成功,要么同时失败!【原子性、隔离性、永久性、一致性】
本文章使用的数据库工具类
JdbcUtils
的代码实现 //www.greatytc.com/p/e908a22f1b82
一、Connection接口中与事务相关的方法
省略void
-
setAutoCommit(boolean autoC)
:- 参数为
true
: 默认值,自动提交 - 参数为
false
: 关闭自动提交,相当于开启事务
- 参数为
-
commit()
: 提交事务【成功之后立即执行】 -
rollback()
: 回滚事务【放在catch语句中,不能放在finally语句中】
二、案例演示
1.数据准备
create database if not exists jdbclearn;
use jdbclearn;
create table account(
id int primary key auto_increment,
name varchar(20),
balance double
);
insert into account (name, balance) values
('Jack', 1000),
('Rose', 1000);
2.jdbc连接实现
// ... 相关包略 ...
public class Test {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
conn.setAutoCommit(false);
String sqlSub = "update account set balance = balance - 500 where name = ?";
String sqlAdd = "update account set balance = balance + 500 where name = ?";
ps = conn.prepareStatement(sqlSub);
ps.setString(1, "Jack");
ps.executeUpdate();
ps = conn.prepareStatement(sqlAdd);
ps.setString(1, "Rose");
ps.executeUpdate();
Scanner input = new Scanner(System.in);
System.out.println("你确认要转?`commit` or `rollback` ?");
String command = input.nextLine();
// 使用反射实现的!
Method exe = conn.getClass().getMethod(command);
exe.invoke(conn);
JdbcUtils.close(conn, ps, rs);
} catch (Exception e) { System.out.println("出现了未知错误!");
}finally { JdbcUtils.close(conn, ps, rs); }
}
}