2013-07-31 29 views
1

我很高興與來自Java的DatatBases工作,我一直想知道我是否以正確的方式工作。在我的代碼中,所有數據庫接口都在一個名爲DataAccess的類中完成,這是我的代碼示例:正確的方式來更新/從數據庫查詢

請注意,在打開函數isValidOperator()之前,我打開了一個連接(connBlng)。

這是正確的工作方式,還是每次需要訪問數據庫時都應打開和關閉連接?

if(da.StartBlngConnection() == null) 
    return "ERROR" 
DataAccess da = new DataAccess(); 
da.isValidOperator("123")  

//this is code from DataAccess Class 
public Boolean isValidOperator(String dn) { 
    System.out.println(npgReqID + " - " + LOG_TAG + "inside isValidOperator : " + dn); 
    PreparedStatement prepStmt = null; 
    ResultSet queryResult = null; 
    try{ 
     prepStmt = connBlng.prepareStatement("select network_id, network_identifier from operators where network_identifier = ?"); 
     prepStmt.setString(1, dn); 
     queryResult = prepStmt.executeQuery(); 
     if (queryResult.next()) { 
      return true; 
     } 
    }catch(Exception e){ 
     System.out.println(npgReqID + " - " + e); 
     DBLog("", new Date(),"" , npgReqID , "" ,"" , MakeSureNotOutOfRange(GetStackTrace(e),4000), "" , ""); 
     return false; 
    } finally{ 
     closeStatmentandRS(queryResult, PreparedStatement); 
    } 

    return false; 
} 
+0

在finally塊中,您只關閉'queryResult','PreparedStatement'。您必須關閉連接(連接),否則打開的連接數量將超出指定的限制。或者你應該使用某種連接池。 – user75ponic

+0

我在我的程序開始時打開一個單獨的連接,並確保它在最後關閉。 – susparsy

+0

如果你的'connection'在程序執行後關閉,那就沒事了。 – user75ponic

回答

0

JDBC plain不是一個非常易於使用的API。也許你可以看看Dalesbread https://github.com/Blackrush/Dalesbred這是一個輕量級的JDBC包裝器。以下是關於JDBC包裝的常見討論:simple jdbc wrapper

我不會建議一直關閉數據庫連接,您應該爲此使用連接池。通常創建數據庫連接非常昂貴。