JDBC事務處理
事務:一個包含多個步驟的業務操作。如果這個業務被事務管理,要么同時成功,要么同時失敗!【原子性、隔離性、永久性、一致性】
本文章使用的數據庫工具類
JdbcUtils
的代碼實現 http://www.lxweimin.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); }
}
}