Connection

Connection

//定義sql語句  
String sql1 = "update stu set money = 3000 where id = 1";  
String sql2 = "update stu set money = 3000 where id = 2";  
  
//獲取執行sql的對象 statement  
Statement statement = conn.createStatement();  
  
//開啟事務  
  
  
try {  
	//開啟事務管理
    conn.setAutoCommit(false);  
  
    //執行sql  
    int update1 = statement.executeUpdate(sql1);  
  
    //處理結果  
    System.out.println(update1);  
    int i =3/0; // 手動製造異常,此時因為有事務管理
    //所以sql1執行了sql2沒執行,sql1會被rollback
    //執行sql  
    int update2 = statement.executeUpdate(sql2);  
  
    //處理結果  
    System.out.println(update2);  
  
    //提交事務  
    conn.commit();  
} catch (Exception throwable) {  
    //回滾  
    conn.rollback();  
    throwable.printStackTrace();  
}