SonarLint仍然显示阻塞错误,即使我们已经处理了语句,Connection在finally块中关闭

时间:2018-05-29 11:21:14

标签: java sonarlint

SonarLint显示以下错误:

  1. '使用try-with-resources或在“finally”子句中关闭此“Statement”。'
  2. '使用try-with-resources或在“finally”子句中关闭此“Connection” 阻止错误,即使我们已关闭Statement stmt,最后一个块中的Connection con。
  3. 请找到示例代码。

    public String getProductNumber() throws BusinessDelegateException {
    
            String productNo = null;
            Connection con = null;
            Statement stmt = null;
            ResultSet   rs  = null;
            String query  = //some query
            try {
                DataSource ds = getDataSource();
                con = ds.getConnection();
                stmt = con.createStatement();
                rs   = stmt.executeQuery(query);
                productNo =.......
                ....................
            }catch (Exception e) {
                String errorMsg = "Error occured in getProductNumber()";
                throw new BusinessDelegateException(errorMsg, e);
            }finally{
                try {
                    if(rs != null)
                        rs.close();
                    if (stmt != null)
                        stmt.close();
                    if (con != null)
                        con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            return productNo;
        }
    

    我们能够通过以下方式修改finally块来解决问题。但似乎仍然重复捕获块。我们可以通过其他方式解决这个问题吗?

    finally{
            try {
                if(rs != null)
                    rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (con != null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    

1 个答案:

答案 0 :(得分:0)

如果没有try-with-resources,你只能通过使用重用性方法改进代码,调用main方法:

closeResources(rs, stmt, con);

这将为每个资源调用一个不同的方法,例如Statement:

 public void closeResource(Statement stmt) {
    if (stmt != null) {
        stmt.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
顺便说一下,您最好使用记录器而不是e.printStackTrace()

要获得完整的解决方案,您可以检查extensive example在数组中添加资源并在循环中关闭它们:

for (Closeable resource : resources) {
   try {
     resource.close();
相关问题