使用语句和结果集管理多个查询可选查询

时间:2012-08-17 18:01:14

标签: java try-catch resultset

目前我们有一个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);
 }
}

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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
}//