如何在SonarCloud上解决此问题?

时间:2019-12-29 10:58:45

标签: java sonarqube sonarcloud

使用SonarCloud我收到了这个 bug

Use try-with-resources or close this "ResultSet" in a "finally" clause

这是以下代码:

public long executeUpdate() throws SQLException {
    if (query != null) {
        try {
            statement.execute();
            if (returnGeneratedKeys) {
                ResultSet resultSet = statement.getGeneratedKeys();
                if (resultSet.next()) {
                    return resultSet.getLong(1);
                }
            }
        } finally {
            statement.close();
            connection.close();
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您可以这样做:

public long executeUpdate() throws SQLException {
    if (query != null) {
        try {
            statement.execute();
            if (returnGeneratedKeys) {
                try (ResultSet resultSet = statement.getGeneratedKeys()) {
                    if (resultSet.next()) {
                        return resultSet.getLong(1);
                    }
                }
            }
        } finally {
            statement.close();
            connection.close();
        }
    }
    return 0;
}

以下结构:

try (ResultSet resultSet = statement.getGeneratedKeys()) {
    if (resultSet.next()) {
        return resultSet.getLong(1);
    }
}

等于:

ResultSet resultSet = statement.getGeneratedKeys()
try {
    if (resultSet.next()) {
        return resultSet.getLong(1);
    }
} finally {
    if (resultSet != null) {
        resultSet.close()
    }
}