如果使用自定义关闭方法 (java 6),如何避免声纳错误 "use try-with-resources or close this ... in a "finally"clause"?

How to avoid sonar error "use try-with-resources or close this ... in a "finally" clause" if custom close method is used (java 6)?

代码如下:

Connection connection = null;
    try {
        connection = createConnection();
        String sql = String.format(STRING_FOR_PROCEDURE, name);
        connection.createStatement().execute(sql);
        connection.commit();
    } catch (Exception e) {
        throw new DatabaseServiceException(e.getMessage(), e);
    } finally {
        closeConnection(connection);
    }

我想声纳希望我用这样的东西“最终”关闭块中的连接:

connection.close();

但是我为此使用了自定义方法:

    protected void closeConnection(Connection connection) {
    try {
        if (connection != null) {
            connection.close();
        }
    } catch (SQLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
}

当前class需要使用此方法。但我收到声纳拦截器“使用 try-with-resources 或在“finally”子句中关闭此语句”。 有什么解决办法吗?

声纳有助于设计正确的代码,但有时如果您很清楚我们可以忽略警告..但是是的,你能做到吗?

Connection connection = null;
    try {
        connection = createConnection();
        String sql = String.format(STRING_FOR_PROCEDURE, name);
        connection.createStatement().execute(sql);
        connection.commit();
    } catch (Exception e) {
        throw new DatabaseServiceException(e.getMessage(), e);
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
        }
    }

请注意,您的错误是“在“finally”子句中使用 try-with-resources 或关闭此 语句 。”

问题不在于您如何关闭连接。问题是您没有关闭声明。

Connection connection = null;
Statement statement = null;
try {
    connection = createConnection();
    String sql = String.format(STRING_FOR_PROCEDURE, name);
    statement = connection.createStatement();
    statement.execute(sql);
    connection.commit();
} catch (Exception e) {
    throw new DatabaseServiceException(e.getMessage(), e);
} finally {
    if (statement != null) {
        try {
            statement.close();
        } catch (SQLException e) {
            Logger.log(Level.SEVERE, "Could not close Statement.", e);
        }
    }
    closeConnection(connection);
}

记住在关闭Connection之前需要先关闭语句。