2014-07-02 149 views
0

我在做代碼審查,並且在很多情況下,如果SQL語句返回記錄,我發現結果未關閉。 SQL語句的業務規則僅考慮第一條記錄。Java返回SQL語句

下面是我困惑的代碼,爲什麼它返回的值沒有關閉結果集和語句?這是正確的方法嗎?

if (rs.next()){ 
     return new Long(rs.getLong(1)); 
} 

下面是示例代碼:

private static Long <MethodName> 
    (
     oracle.sql.NUMBER[] o_errorCode, 
     oracle.sql.CHAR[] o_errorText, 
     Long portA, 
     Long portZ) throws SQLException 
    { 
     String errorMessage = ""; 
     Long[] NROLE = new Long[1]; 
     Long[] pTask = new Long[1]; 
     Long dimObject = null; 
     Long objectIDA = null; 
     Long objectIDZ = null; 
     Long relation = null; 
     Connection tmpConn = null; 
     Statement stmt = null; 
     ResultSet rs = null; 
     String SQL = null; 
     try 
     { 
      // Retrieve the Epipe circuits that are on the specified ports 
      stmt = DbUtil.getConn().createStatement(); 
      String query = "Select * from Circuit where ... Order by Id"; 
       rs = stmt.executeQuery(query); 
       if (rs.next()){ 
        return new Long(rs.getLong(1)); 
       } 
       rs.close(); 
       stmt.close(); 
      return null; 
     } 
     catch (SQLException ex) 
     { 
      o_errorCode[0] = new oracle.sql.NUMBER(1); 
      o_errorText[0] = new oracle.sql.CHAR("SQLException - " + ex.getMessage(), 
      oracle.sql.CharacterSet.make(oracle.sql.CharacterSet.DEFAULT_CHARSET)); 
      return(null); 
     } 
     catch (Exception e) 
     { 
      o_errorCode[0] = new oracle.sql.NUMBER(1); 
      o_errorText[0] = new oracle.sql.CHAR("Exception - " + e.getMessage(), oracle.sql.CharacterSet.make(
      oracle.sql.CharacterSet. 
      DEFAULT_CHARSET)); 
      return(null); 
     } 
} 
+0

如何管理'finally'塊資源收? –

回答

0

使用finally

try { 
      // Retrieve the Epipe circuits that are on the specified ports 
      stmt = DbUtil.getConn().createStatement(); 
      String query = "Select * from Circuit where ... Order by Id"; 
      rs = stmt.executeQuery(query); 
      if (rs.next()) { 
       return new Long(rs.getLong(1)); 
      } 

      return null; 
     } catch (SQLException ex) { 

     } catch (Exception e) { 

     } finally { 
      rs.close(); 
      stmt.close(); 
     } 
2

不正確,因爲Java 7的使用try-與資源時,很容易解決:

try (ResultSet rs = statement.executeQuery()) { 
    if ... 
     return ... 
} 

if rs.next()可能有更好的SQL做的:一種limit或MIN (Id)的一種。

這是不好的風格太:

  1. 使用一貫的風格:SELECT FROM WHERE ORDER BYselect from where by
  2. 請勿使用數據庫特定的類; JDBC花費了很多精力來不需要它。
  3. 我幾乎懷疑這裏可能已經使用了PreparedStatement。除了防止SQL注入它很好地轉義參數。
0

正確的地方,關閉數據庫資源,如結果集,語句或連接是try-catch語句的終於塊。因爲,JVM在任何情況下訪問此塊。

以下使用是安全的:

ResultSet rs = null; 
Statement stmt = null; 
Connection conn = null; 
try { 
    conn = SomeDBUtility.getConnection(); 
    stmt = conn.createStatement(); 
    rs = stmt.executeQuery("<Your SQL string>"); 
} catch (SQLException e) { 
    // handle the exception 
} finally { 
    rs.close(); 
    stmt.close(); 
    conn.close(); 
}