执行完整的说明



首先,我找不到适合此帖子的标题,因此当前的标题似乎不合适。

第二,让我解释一下我的需求,我正在尝试执行一系列代码的块:

 updateDataBase();
 instruction1();
 instruction2();

在执行结束时,我想确保指令1((和指令2((已经完全成功,否则会进行某种回滚以取消UpdatedAtabase((。

是否有一种方法可以管理此问题,而无需使用新方法来撤消更新的base((方法。

这是我在评论中所说的...这将使逻辑放在updatedatabase((方法中。

public void updateDatabase() throws Exception {
    PreparedStatement updateStmt = null;
    String updateString = "some sql code";
    // save point to roll back to... 
    Savepoint savepoint = con.setSavepoint();    
    try {
        // disable auto commit
        con.setAutoCommit(false);
        updateStmt = con.prepareStatement(updateString);
        updateStmt.executeUpdate();
        // call instructions
        instruction1();
        instruction2();
        // if we get here then all is good, commit
        con.commit();
    } catch (Exception e ) {
        // if we get here then instruction 1 or 2 failed... rollback
        if (con != null) {
            try {
                System.err.print("Transaction is being rolled back");
                con.rollback(savepoint);
            } catch(SQLException excep) {
                // log error
            }
        }
    } finally {
        if (updateStmt != null) {
            updateStmt.close();
        }
        // set connection back to auto-commit
        con.setAutoCommit(true);
    }
}

异常捕获,然后重新插入,以便在回滚后负责的其他部分可以适当处理。下一个级别将是定义扩展异常的自定义指令failedExecting,以便您在异常处理中具有一些粒度。

private void execute() throws Exception {
  try {
   updateDataBase();
   instruction1();
   instruction2();
  } catch(Exception ex){
    // new rollback 
    rollBack();
    throw ex;
  }
}

最新更新