当前,我们有一个Java应用程序,它具有许多不同的查询,并且并不是所有的查询都在一个特定的时间运行。因此,对于每个查询,我们计划有一个新的语句和结果集并立即关闭它们?下面是我们现在如何运行查询的代码片段。我们试图用try and 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);
}
}
最佳答案
为了使回滚起作用,必须首先检查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
}