2014-10-20 145 views
0

我用靜態代碼分析器掃描了我的代碼,並得到未釋放資源:數據庫錯誤。我正在關閉所有的db連接,下面是我的代碼快照。靜態代碼分析註釋

public String methodInDAO(Bean bean) throws SQLException ,Exception 
{ 

    Session session = null; 
    Connection connection = null; 
    ResultSet resultSet1 = null; 
    CallableStatement callableStatement = null; 

    try { 
     connection = dataSource.getConnection(); 
     callableStatement = connection.prepareCall(query); 
     resultSet1 = callableStatement.execute(); 
     //code operations 
    } finally { 
     if(null != callableStatement) 
      callableStatement.close(); 

     resultSet1 = null; 
     callableStatement = null; 

     if(null != connection) 
      connection.close(); 

     if (null != session) 
      session.close(); 

    } 

    return returnOutput; 
} 

所有拋出的異常都在服務層處理。任何人都可以建議數據源不在哪裏發佈?

+0

如果'connection.close()'拋出異常會發生什麼?該連接是否仍然打開或關閉? – Tom 2014-10-20 12:45:33

+0

'resultSet1 = null;'不關閉結果集。在關閉callableStatement之前,您應該使用'resultSet1.close()'。 [ResultSet.close](http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#close())拋出SQLException,所以你應該使用try {} catch()在關閉資源時阻止,以避免重寫初始異常。 – Daniel 2014-10-20 12:53:13

+0

拋出的任何異常都是在服務層處理的,所以finally塊中拋出的異常也包含在同一個中。 – jain626 2014-10-27 09:31:16

回答

3

如果您的JDBC驅動程序支持JDBC 4.1,則可以使用try-with-resources

try (connection = dataSource.getConnection(); 
    callableStatement = connection.prepareCall(query)) { 
    results = callableStatement.execute(); 
    // code operations 
} 

使用一個try-與資源聲明Connection類型,ResultSet的自動關閉資源的能力,並Statement

加入到JDBC 4.1。

+0

雖然這是一個很好的使用模式,但請注意,即使在今天,許多靜態分析引擎仍未正確識別try- with-resources模式作爲資源的有效版本。但是這就是他們的錯誤。 – AviD 2017-08-01 14:51:03