Java关闭连接和findbugs

Jim*_*Jim 3 java database findbugs

在我们的代码中,我们通常使用以下模式:

Connection conn;
try{
    conn = getConnection();
    //Do databasey stuff
}catch(Exceptions that get thrown){
}finally{
    try{
        conn.close();
    }catch(SQLException ex){
        logger.error("Failed to cleanup database connection",ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,findbugs不喜欢这个.由于conn.close()可以抛出异常,因此无法保证关闭连接.findbugs是否过于迂腐或是否有更好的方法来关闭数据库连接.

编辑:添加删除尝试捕获关闭.

Buh*_*ndi 6

已经有一个实用程序可以完成@duffymo提到的:Apache的DbUtils.

  • DbUtils.close(ResultSet);
  • DbUtils.close(Statement);
  • DbUtils.close(Connection);

APIDocs显示所有可用的方法.


更新

这是一个例子:

import org.apache.commons.dbutils;


Connection conn;
try{
    conn = getConnection();
    //Do databasey stuff
} catch(Exception e){
    //throw a glorious exception....
} finally{
    DbUtils.closeQuietly(conn); //This hides the SQLException thrown by conn.close();
    //or 
    //DbUtils.close(conn);
}
Run Code Online (Sandbox Code Playgroud)

更新:正如ArtB所建议的那样,如果您最终关闭资源和连接并且findBugs是一个唠叨,您可以添加以下注释(在方法之上).

@edu.umd.cs.findbugs.annotations.SuppressWarnings("OBL_UNSATISFIED_OBLIGATION")
Run Code Online (Sandbox Code Playgroud)


Sle*_*led 6

你真正想做的是将"The Elite Gentleman"的答案与@edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" )注释结合起来.如果你以下面的方式完成关闭方法,那么FindBugs似乎很高兴(这是btw这样做的首选顺序):

...
}finally{
    try{ 
       resultSet.close();
    }catch( SqlException e ){
       //log error
    }finally{
       try{
          statement.close();
       }catch( SqlException e ){
          //log error
       }finally{
          try{
              connection.close();
          }catch( SqlException e ){
              //log error
          }
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是非常冗长的,你可能不想做,如果没有其他原因,而不是你的腕管的爱,所以你应该使用该DBUtils.closeQuietly()方法(或创建自己的,你的电话).但是,FindBugs无法识别这一点(即使用库或您自己的方法)正确关闭资源并向您发出警告.在这种情况下,这显然是误报.因此,必须确保它是您获得的唯一警告,然后禁用该方法的特定警告.

@edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" )
public void doStuff( final Connection connection ){
    try{
        //Do databasey stuff
    }catch( SqlException e ){
        //throw a glorious exception....
    }finally{
        DbUtils.closeQuietly( resultSet  );
        DbUtils.closeQuietly( statement  );
        DbUtils.closeQuietly( connection );
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以使用几行代码清理资源,并避免使用FindBugs警告.