Java操作資料庫——在JDBC裡使用事務
摘要:本文主要學習了如何在JDBC裡使用事務。
使用Connection的事務控制方法
當JDBC程式向資料庫獲得一個Connection對象時,預設情況下這個Connection對象會自動向資料庫送出發送的SQL語句。若想關閉這種預設送出方式,讓多條SQL在一個事務中執行,可使用JDBC提供的事務控制方法。
常用方法
查詢自動送出的狀态:boolean getAutoCommit() throws SQLException;
設定自動送出的狀态:void setAutoCommit(boolean autoCommit) throws SQLException;
設定還原點:Savepoint setSavepoint() throws SQLException;
設定指定名稱的還原點:Savepoint setSavepoint(String name) throws SQLException;
删除指定名稱的還原點:void releaseSavepoint(Savepoint savepoint) throws SQLException;
送出:void commit() throws SQLException;
復原:void rollback() throws SQLException;
復原到指定名稱的還原點:void rollback(Savepoint savepoint) throws SQLException;
查詢隔離級别:int getTransactionIsolation() throws SQLException;
設定隔離級别:void setTransactionIsolation(int level) throws SQLException;
使用執行個體
1 public static voidmain(String[] args) {2 Properties pros = newProperties();3 try{4 pros.load(TestConnection.class.getClassLoader().getResourceAsStream("jdbc.properties"));5 } catch(IOException e) {6 e.printStackTrace();7 }8 try{9 Class.forName(pros.getProperty("driverClass"));10 } catch(ClassNotFoundException e) {11 e.printStackTrace();12 }13 Connection conn = null;14 PreparedStatement pstmt = null;15 try{16 String url = pros.getProperty("url");17 String user = pros.getProperty("user");18 String password = pros.getProperty("password");19 conn =DriverManager.getConnection(url, user, password);20 boolean status =conn.getAutoCommit();21 System.out.println("AutoCommit = " +status);22 conn.setAutoCommit(false);23 pstmt = conn.prepareStatement("delete from student where id = 906");24 pstmt.executeUpdate();25 int e = 1 / 0;//模拟出現異常
26 pstmt = conn.prepareStatement("delete from student where id = 907");27 pstmt.executeUpdate();28 conn.commit();//手動送出,不能省略
29 } catch(Exception e) {30 e.printStackTrace();31 try{32 conn.rollback();//手動復原,可以省略,系統會自動復原
33 } catch(SQLException ex) {34 ex.printStackTrace();35 }36 } finally{37 try{38 pstmt.close();39 } catch(SQLException e) {40 e.printStackTrace();41 }42 try{43 conn.close();44 } catch(SQLException e) {45 e.printStackTrace();46 }47 }48 }