事務將一組SQL語句視為一個邏輯單元,如果任何語句失敗,整個事務將失敗并回滾。
默認情況下,JDBC連接處于自動提交模式,這意味著每個SQL語句在完成后都提交到數據庫。
要啟用手動事務,請使用Connection對象的setAutoCommit()方法。
例如,以下代碼關閉自動提交:
conn.setAutoCommit(false);
要提交更改,請在連接對象上調用commit()方法,如下所示:
conn.commit( );
要回滾對數據庫的更新,請使用以下代碼:
conn.rollback( );
以下示例顯示如何使用提交和回滾。
try{ conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String SQL = "INSERT INTO Employees VALUES (1, "name")"; stmt.executeUpdate(SQL); String SQL = "INSERT INTO Employees VALUES (2, "anotherName")"; stmt.executeUpdate(SQL); conn.commit(); }catch(SQLException se){ conn.rollback(); }
保存點定義事務中的回滾點。
如果在保存點之后發(fā)生錯誤,我們可以回滾以撤消所有更改或僅撤消在保存點之后進行的更改。
Connection對象有兩個方法與保存點相關。
setSavepoint(String savepointName)
定義新的保存點。它還返回一個Savepoint對象。
releaseSavepoint(Savepoint savepointName)
刪除保存點。它需要一個Savepoint對象作為參數,它由setSavepoint()方法生成。
rollback(String savepointName)
方法將工作回滾到指定的保存點。
以下示例說明了使用Savepoint對象:
try{ conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Savepoint savepoint1 = conn.setSavepoint("Savepoint1"); String SQL = "INSERT INTO Employees VALUES (1, "name")"; stmt.executeUpdate(SQL); String SQL = "INSERT INTO Employees VALUES (2, "new name")"; stmt.executeUpdate(SQL); conn.commit(); }catch(SQLException se){ conn.rollback(savepoint1); }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class Main { private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:YourDatabase"; private static final String DB_USER = "user"; private static final String DB_PASSWORD = "password"; public static void main(String[] argv) throws Exception { Class.forName(DB_DRIVER); Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); PreparedStatement preparedStatementInsert = null; PreparedStatement preparedStatementUpdate = null; String insertTableSQL = "INSERT INTO Person" + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES" + "(?,?,?,?)"; String updateTableSQL = "UPDATE Person SET USERNAME =? " + "WHERE USER_ID = ?"; java.util.Date today = new java.util.Date(); dbConnection.setAutoCommit(false); preparedStatementInsert = dbConnection.prepareStatement(insertTableSQL); preparedStatementInsert.setInt(1, 9); preparedStatementInsert.setString(2, "101"); preparedStatementInsert.setString(3, "system"); preparedStatementInsert.setTimestamp(4, new java.sql.Timestamp(today.getTime())); preparedStatementInsert.executeUpdate(); preparedStatementUpdate = dbConnection.prepareStatement(updateTableSQL); preparedStatementUpdate.setString(1, "new string"); preparedStatementUpdate.setInt(2, 999); preparedStatementUpdate.executeUpdate(); dbConnection.commit(); dbConnection.close(); } }
更多建議: