简体   繁体   中英

How can I resolve this issue on SonarCloud?

Using SonarCloud I got this bug :

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

This is the following code:

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

You may do this:

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

The following structure:

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

is equal to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM