簡體   English   中英

SonarQube 不斷抱怨 Use try-with-resources 或在“finally”子句中關閉此“PreparedStatement”

[英]SonarQube keeps complaining about Use try-with-resources or close this "PreparedStatement" in a "finally" clause

我正在嘗試根據用戶的 ID 從表中獲取電子郵件。 但是,SonarQube 一直在抱怨Use try-with-resources or close this "PreparedStatement" in a "finally" clause我已經擁有Use try-with-resources or close this "PreparedStatement" in a "finally" clause 我已經看過這里和其他地方的答案,但這些解決方案對我不起作用。 這是代碼:

public String getUserEmail(String id) throws SQLException {
        String emailAddress = null;
        String sql = "select email from my_table where id=?";
        PreparedStatement preparedStatement = this.connection.prepareStatement(sql);
        preparedStatement.setString(1, id);
        try {
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                emailAddress = rs.getString("email");
            }
        } catch(SQLException e) {
            throw new TuringClientException("Failed to getUserEmail. ", e);
        } finally {
            preparedStatement.close();
        }
        return emailAddress;
    }

我也嘗試將PreparedStatement preparedStatement = this.connection.prepareStatement(sql)包裝在另一個 try catch 或嵌套 try-catch 中,但沒有任何嘗試有效。

您可以嘗試(嘗試使用資源)

public String getUserEmail(String id) throws SQLException {
        String emailAddress = null;
        String sql = "select email from my_table where id=?";
        try(PreparedStatement preparedStatement = this.connection.prepareStatement(sql)) {
            preparedStatement.setString(1, id);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                emailAddress = rs.getString("email");
            }
        } catch(SQLException e) {
            throw new TuringClientException("Failed to getUserEmail. ", e);
        }
        return emailAddress;
    }

setString可能會拋出SQLException 如果語句准備成功,然后setString拋出異常,它將在try之外執行,並且該語句將永遠不會被關閉。 prepareStatement移動到嵌套的try應該沒問題,只要你在正確的finally塊中有clsoe (並且沒有看到你做了什么,很難說為什么 SonarQube 抱怨它),但老實說,使用 try-with -resource 語法會更簡潔。 請注意,順便說一下, ResultSet也應該關閉:

public String getUserEmail(String id) throws SQLException {
    String emailAddress = null;
    String sql = "select email from my_table where id=?";
    try (PreparedStatement preparedStatement = this.connection.prepareStatement(sql) {
        preparedStatement.setString(1, id);
        try (ResultSet rs = preparedStatement.executeQuery()) {
            while (rs.next()) {
                emailAddress = rs.getString("email");
            }
        } catch(SQLException e) {
            throw new TuringClientException("Failed to getUserEmail. ", e);
        }
    }
    return emailAddress;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM