0

目前我们有一个 java 应用程序,它有许多不同的查询,并不是所有的查询都在一个特定的时间运行。因此,对于每个查询,我们计划有一个新的语句和结果集并立即关闭它们?下面给出了我们现在如何运行查询的代码片段。我们尝试使用 try 和 catch 覆盖每个查询,但是如果查询失败,则回滚在全局级别上不起作用。如何最好地将它们放在适当的位置以确保也没有内存泄漏?

try{ //main try outside

//lots of inner queries run based on some logics of if else etc


//sample query of opening and closing both statement and resultsets.

Statement stmt1 = null;
stmt1 = dbconn.createStatement();
String selectQuery1  = "Select query";
ResultSet rs1 = stmt1 .executeQuery(selectQuery1);
while(rs1.next()) {
//process here

}
try{
  if (rs1 != null ){
     rs1.close();
  }
  if (stmt1!= null ){
    stmt1.close()
  }
}
catch(SQLException ex){
ex.printStackTrace(System.out);
}

dbconn.commit();
}
catch (SQLException ex) { 
 try {    
   dbconn.rollback();  
 } 
 catch (Exception rollback){    
  rollback.printStackTrace(System.out);
 }
}
catch (Exception e){
 try{    
    dbconn.rollback();  
 } 
 catch (Exception rollback) {    
   rollback.printStackTrace(System.out);
 }
}
4

2 回答 2

1

要使回滚工作,您必须首先检查是否autoCommit设置为false最初。只有在所有操作都已成功执行时,您才想提交。

这样做的一种方法可能是使用这样的结构:

Connection connection = getDBConnection(); //Depends on how you get your connection
boolean autoCommit = connection.getAutoCommit();
try{
    //Set autoCommit to false. You will manage commiting your transaction
    connection.setAutoCommit(false); 
    //Perform your sql operation

    if(doCommit){ //all your ops have successfully executed, you can use a flag for this
        connection.commit();
    }
}catch(Exception exe){
    //Rollback
}finally{
    connection.setAutoCommit(autoCommit); //Set autoCommit to its initial value
}
于 2012-08-17T18:20:01.537 回答
1
Please try keeping dbconn.setAutoCommit(false) as first statement in your first try block so that it will not insert/update/delete query unless you say dbconn.commit()


try{
       conn.setAutoCommit(false);
      Statement stmt1 = null;
      stmt1 = dbconn.createStatement();
      String selectQuery1  = "Select query";
      ResultSet rs1 = stmt1 .executeQuery(selectQuery1);
      while(rs1.next()) {
        //process here

      } 
      conn.commit();

      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
      try{
         if(conn!=null)
            conn.rollback();
      }catch(SQLException se2){
         se2.printStackTrace();
      }//end try

   }catch(Exception e){
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(rs!=null)
            rs.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
}//
于 2012-08-17T18:23:23.107 回答