0

使用SonarCloud我得到了这个错误

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

1 回答 1

2

你可以这样做:

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()
    }
}
于 2019-12-30T13:36:38.317 回答