2017-05-24 69 views
0

在我們的代碼中,我們已經關閉了結果集,最後仍然阻止聲納表明它永遠不會關閉。請幫助。我們已經使用Spring數據源實用程序創建了連接,並使用相同的連接釋放了連接池。結果集從未關閉 - Sonarqube分析

try { 
    con = DataSourceUtils.getConnection(dataSource); // connection to database using spring 
    stmt = con.createStatement(); 
    rs = stmt.executeQuery("<>"); 
    . 
    . 
} 
catch (Exception e) { 
} 
finally { 
    if (stmt != null && !stmt.isClosed()) { 
    stmt.close(); 
    } 
    if (rs != null && !rs.isClosed()) { 
    rs.close(); 
    } 
    if (con != null) { 
    DataSourceUtils.releaseConnection(con, dataSource); 
    } 
} 
+2

鑑於你已經顯示的構造,你可以轉換爲使用'嘗試與資源'的方法,那麼你可以擺脫finally塊(主要是)。 – KevinO

+0

不要相信SonarQube;它往往是錯誤的,有時甚至是錯誤的。 – DavidW

+0

謝謝凱文......!截至目前,我無法使用該選項...!我找到了解決方案,並已在下面給出它!它真的很難破解什麼聲納認爲 –

回答

1

你應該使用try-與資源語句來清理你的代碼,並確保正確的資源處理:

try (final Connection con = DataSourceUtils.getConnection(dataSource); // connection to database using spring 
    final Statement stmt = con.createStatement(); 
    final ResultSet rs = stmt.executeQuery("<>");) { 
    ... 
} catch (Exception e) { 
    // handle Exceptions here 
} 
+0

謝謝DPR ..這是正確的選擇。但客戶還沒有準備好改變它,因爲它可能涉及更大的測試範圍。 –

2

這可能

stmt.close(); 

到拋出SQLException。如果發生這種情況,那麼

rs.close(); 

將永遠不會執行。正如其他人所建議的,考慮使用try with resource

0

最後我發現了爲什麼Sonar會拋出錯誤,即使我們已經關閉了資源。

Sonar希望每個資源在單獨的嘗試捕獲中分別關閉。 sis背後的原因是,如果一旦資源關閉導致問題,其他人可能會被打開。

這樣,

finally{ 
try{ 
if(resultset!=null){ 
resultset.close(); 
} 
catch(SQLException e){ 
--- 
--- 
} 
if(connection!=null){ 
connection.close(); 
} 
catch(SQLException e){ 
--- 
--- 
} 
} 

再在上面的代碼,請在例外添加logger.error避免聲納另一個錯誤! ! :) logger.error("", e);