2014-10-20 72 views
0

我用静态代码分析器扫描了我的代码,并得到未释放资源:数据库错误。我正在关闭所有的db连接,下面是我的代码快照。静态代码分析注释

public String methodInDAO(Bean bean) throws SQLException ,Exception 
{ 

    Session session = null; 
    Connection connection = null; 
    ResultSet resultSet1 = null; 
    CallableStatement callableStatement = null; 

    try { 
     connection = dataSource.getConnection(); 
     callableStatement = connection.prepareCall(query); 
     resultSet1 = callableStatement.execute(); 
     //code operations 
    } finally { 
     if(null != callableStatement) 
      callableStatement.close(); 

     resultSet1 = null; 
     callableStatement = null; 

     if(null != connection) 
      connection.close(); 

     if (null != session) 
      session.close(); 

    } 

    return returnOutput; 
} 

所有抛出的异常都在服务层处理。任何人都可以建议数据源不在哪里发布?

+0

如果'connection.close()'抛出异常会发生什么?该连接是否仍然打开或关闭? – Tom 2014-10-20 12:45:33

+0

'resultSet1 = null;'不关闭结果集。在关闭callableStatement之前,您应该使用'resultSet1.close()'。 [ResultSet.close](http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#close())抛出SQLException,所以你应该使用try {} catch()在关闭资源时阻止,以避免重写初始异常。 – Daniel 2014-10-20 12:53:13

+0

抛出的任何异常都是在服务层处理的,所以finally块中抛出的异常也包含在同一个中。 – jain626 2014-10-27 09:31:16

回答

3

如果您的JDBC驱动程序支持JDBC 4.1,则可以使用try-with-resources

try (connection = dataSource.getConnection(); 
    callableStatement = connection.prepareCall(query)) { 
    results = callableStatement.execute(); 
    // code operations 
} 

使用一个try-与资源声明Connection类型,ResultSet的自动关闭资源的能力,并Statement

加入到JDBC 4.1。

+0

虽然这是一个很好的使用模式,但请注意,即使在今天,许多静态分析引擎仍未正确识别try- with-resources模式作为资源的有效版本。但是这就是他们的错误。 – AviD 2017-08-01 14:51:03