2017-04-01 33 views
0

我正在學習MySQL數據庫,我不能理解一個概念。假設在同一個類中有兩個方法,如下所示。現在,我必須使用Connection connect = dbConnection.getDBConnection();每種方法還是有不同的方法來聲明一個連接並在多個方法?:MYSQL一個類的一個連接

private void setUpdateButton(ActionEvent event) { 
    try{ 
     Connection connect = dbConnection.getDBConnection(); 
     Statement stmt = connect.createStatement(); 


     if(txtID.getText().trim().isEmpty()||txtFirstName.getText().trim().isEmpty() || txtSecondName.getText().trim().isEmpty() || 
       txtGender.getText().trim().isEmpty() || txtAge.getText().trim().isEmpty() || txtHomeAddress.getText().trim().isEmpty() || txtPhoneNumber.getText().trim().isEmpty()) { 
      showAlert("Invalid Input!", "All fields need to be populated before updating."); 
     }else { 
       String sqlQuery ="update student_information set Age ='"+Integer.parseInt(txtAge.getText())+"',Name ='"+txtFirstName.getText()+"',Surename='"+txtSecondName.getText() 
      +"',Gender='"+txtGender.getText()+"',Address='"+txtHomeAddress.getText()+"',PhoneNumber='"+txtPhoneNumber.getText()+"'where ID="+Integer.parseInt(txtID.getText()); 
       stmt.executeLargeUpdate(sqlQuery); 
       setTxtArea(); 
       showConfAlert("Update Completed!", "Record has been updated!"); 
+0

您可以使** connect **對象爲全局類型,但您需要意識到數據庫連接將保持打開狀態,直到您使用** connect.close()**關閉它爲止。你當然也需要從你的方法中刪除所有的connect.close()。您應該總是**在完成後關閉數據庫連接。我個人喜歡你現在這樣做的方式,但又一次......這一切都取決於你的行爲。 – DevilsHnd

+0

這是否意味着使用Connection connect = dbConnection.getDBConnection();在每一種連接方法中都是正確的做法?對我來說這似乎很奇怪,我需要在每種方法中創建一個新的連接。感謝您的回覆 – helloumarian

+0

在我看來....是的。連接應該在finally {}塊中關閉(以及ResultSet和Statement對象)以釋放數據庫資源。這完全取決於你在數據庫會話期間所做的事情。 – DevilsHnd

回答

0

創建連接是一種昂貴的操作,所以我覺得你應該打開的應用程序啓動的連接,並關閉使用它在出口。

如果你的程序不是多線程,你可以使用簡單的全局對象,否則應該使用其他策略。

您可以使用返回連接的方法爲您的應用程序創建一個單例。

public class App { 
    private static App self; 

    private Connection connection; 

    private App(){ 
    } 

    public synchronized App getInstance(){ 
     if(self == null){ 
      self = new App(); 
     } 
     return self; 
    } 


    public synchronized Connection getConnection()throws SQLException { 
     if(connection==null || !isValid(connection)){ 
      // Create a new connection 
     } 
     return connection; 
    } 

    private boolean isValid(Connection conn) { 
     // Check if the connection is valid otherwise return false 
     return false; 
    } 


    public static synchronized void close(){ 
     try{ 
      self.connection.close(); 
     } catch (SQLException e){ 
      // Swallow exception 
     } finally { 
      self = null; 
     } 
    } 

} 

你可以得到連接的地方是這樣的:

Connection conn = App.getInstance().getConnection(); 

您應該確保關閉退出的連接,可能與關閉掛鉤。

您還可以,創建一個在你連接轉發所有的連接方法,原來的連接,配合緊密的異常標誌着連接可用,這樣你創造這樣1個連接池的包裝。

如果連接可用,則返回它,否則您要麼等待或拋出,要麼執行最適合您應用程序的操作。