2015-04-06 93 views
0

我想編寫在MySQL數據庫上運行的小應用程序。 但是閱讀本兩個主題後下面我糊塗了什麼是連接到數據庫工作的正確方法:在JavaFX應用程序中打開和關閉連接

is it safe to keep database connections open for long time

Closing Database Connections in Java

一說,我應該保持很長一段時間,語句簡短連接第二,我應該儘快結束一切。

哪個更好/正確的方法?

例1:

private void query(){ 
     final String query = "SELECT * FROM database;"; 
     MysqlDataSource dataSource = new MysqlDataSource(); 
     dataSource.setServerName("localhost"); 
     dataSource.setDatabaseName("database"); 
     dataSource.setUser("root"); 
     dataSource.setPassword("password"); 

     try(Connection connection = dataSource.getConnection()){ 
      try(PreparedStatement preparedStatement = connection.prepareStatement(query)){ 
       try(ResultSet resultSet = preparedStatement.executeQuery()){ 
        //--- working with resultset 
       } 
      } 
     }catch(Exception exception){ 
      //---- handling exception 
     }; 
    } 

還是好打開連接將持續到應用程序被關閉:

例2:

public class Main extends Application { 

    public static Connection connection; //I will use this everywhere 

    @Override 
    public void start(Stage primaryStage) { 
     //============ opening connection and setting on close request 
     MysqlDataSource dataSource = new MysqlDataSource(); 
     dataSource.setServerName("localhost"); 
     dataSource.setDatabaseName("database"); 
     dataSource.setUser("root"); 
     dataSource.setPassword("password"); 
     try { 
      connection = dataSource.getConnection(); 
      System.out.println("connected to " + dataSource.getDatabaseName()); 
     } catch (SQLException e) { 
      //---- exception 
     } 

     primaryStage.setOnCloseRequest(e->{ 
      try { 
       connection.close(); 
       System.out.println("connection closed"); 
      } catch (Exception exc) { 
       System.err.println("couldn't close connection"); 
      } 
     }); 


     try { 
      BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource(CONSTANTS.ROOT_MAIN_WINDOW.string)); 
      Scene scene = new Scene(root); 
      scene.getStylesheets().add(getClass().getResource("/view/application.css").toExternalForm()); 
      primaryStage.setScene(scene); 
      primaryStage.show(); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

或者你知道更好的方法?

回答

1

你引用的兩個問題沒有矛盾。第一種說法是「長時間保持連接狀態很好」。第二種說法是「當你完成它時你必須關閉連接」。所以只要你願意,你可以保持開放,只要你完成後關閉它。你不能做的是重複打開新的連接,而不是關閉它們。

更具體地說,打開連接是一個耗時的操作。所以你實際上想避免這麼做,保持連接開放是實現這一目標的一種方式。

在服務器端應用程序中,嘗試處理來自多個用戶的請求時,具有單個連接會造成瓶頸。在這種情況下,應使用連接池(應用程序服務器將提供此功能)。在一個客戶端應用程序(如JavaFX應用程序)中,在典型使用中,連接僅用於響應單個用戶的操作,因此重用單個連接是一種合理的方法。

+0

我發現只有第一次連接服務器需要很長時間。當我再次做它時,速度會更快。我現在認爲在第一個例子中使用代碼會更好更安全。 – Tomasz

+0

這聽起來像是數據源實現緩存你的開放連接。所以當你第一次檢索它時,它會打開它;當你「關閉」它(隱式地通過try-with-resources結構)時,它會保持打開狀態,但將其標記爲可用。然後對'getConnection()'的後續調用需要更少的時間。它也可能爲你實現一個池:我不熟悉'MysqlDataSource'。 –

+0

_如果您在需要時打開連接並在完成時將其處理完畢,則不會實際關閉連接,只會將其返回到連接池以再次使用._在此處找到:[link] (http://programmers.stackexchange.com/questions/142065/creating-database-connections-do-it-once-or-for-each-query)你認爲這是一樣的Java? – Tomasz