静态代码分析评论

时间:2014-10-20 12:43:23

标签: java static-analysis

我使用静态代码分析器扫描了我的代码,并获得了 Unreleased Resource:Database 错误。我正在关闭下面的所有数据库连接是我的代码的快照。

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;
}

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

1 个答案:

答案 0 :(得分:3)

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

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

能够使用try-with-resources语句自动关闭ConnectionResultSetStatement

类型的资源

已添加到JDBC 4.1。