JDBC事務操作(轉賬案例)
阿新 • • 發佈:2020-08-27
未使用事務
/* JDBC完成轉賬功能 */ public class Demo01Account { public static void main(String[] args) throws SQLException { //1. 獲取連線Connection物件 Connection con = C3P0Util.getConnection(); //2. Connection物件獲取執行sql語句的Statement物件 Statement stmt = con.createStatement();View Code//3. 定義2條sql語句 String tomSql = "update account set money = money - 1000 where name = 'tom'"; String jerrySql = "update account set money = money + 1000 where name = 'jerry'"; //4. Statement物件調方法執行sql語句,獲取結果 int tomRes = stmt.executeUpdate(tomSql); //5. 處理結果 if (tomRes > 0){ System.out.println("tom扣款1000元成功"); }else { System.out.println("tom扣款1000元失敗"); } int jerryRes = stmt.executeUpdate(jerrySql); if (jerryRes > 0){ System.out.println("jerry收款1000元成功"); }else { System.out.println("jerry收款1000元失敗"); } //6. 關閉資源C3P0Util.release(con,stmt,null); } }
在未使用事務時,預設使用mysql事務處理方式,此時如果出現異常,轉賬將會出現問題。
那麼就需要我們使用事務,將兩條sql語句必須要麼都成功,要麼都失敗。
JDBC使用事務
public class Demo02Account { public static void main(String[] args) { //提升變數作用域 Connection con = null; Statement stmt = null; try { //1. 獲取連線Connection物件 con = C3P0Util.getConnection(); //2. Connection物件開啟事務 con.setAutoCommit(false); //3. Connection物件獲取執行sql語句的Statement物件 stmt = con.createStatement(); //4. 定義2條sql語句 String tomSql = "update account set money = money - 1000 where name = 'tom'"; String jerrySql = "update account set money = money + 1000 where name = 'jerry'"; //5. Statement物件調方法執行sql語句,獲取結果 int tomRes = stmt.executeUpdate(tomSql); int jerryRes = stmt.executeUpdate(jerrySql); //7. 處理結果 if (tomRes > 0){ System.out.println("tom扣款1000元成功"); }else { System.out.println("tom扣款1000元失敗"); } if (jerryRes > 0){ System.out.println("jerry收款1000元成功"); }else { System.out.println("jerry收款1000元失敗"); } //6. 如果sql語句正常執行,沒有出現問題,提交事務 con.commit(); } catch (Exception throwables) { throwables.printStackTrace(); //8. 如果sql語句執行過程中出現問題,回滾事務 if (con != null) { try { con.rollback(); } catch (SQLException e) { e.printStackTrace(); } } } finally { //9. 關閉資源 C3P0Util.release(con,stmt,null); } } }View Code
手動建立異常(此時回滾事務,兩條sql語句都不會執行)