打开和关闭JavaFX应用程序中的连接

时间:2015-04-06 20:26:13

标签: mysql database-connection javafx-8

我想在MySQL数据库上编写很少的应用程序。 但是在阅读下面的这两个主题后,我感到困惑的是使用Connection to database的正确方法是什么:

is it safe to keep database connections open for long time

Closing Database Connections in Java

有人说我应该长时间保持Connection,并且声明要短,其次要我尽快关闭所有内容。

哪种方式更好/更合适?

示例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 个答案:

答案 0 :(得分:2)

你引用的两个问题之间没有矛盾。第一个说“长时间保持连接打开是好的。”第二个说“完成后必须关闭连接”。所以你可以随意打开它,只要你完成它就关闭它。你不能做的是反复打开新的连接而不是关闭它们。

更具体地说,打开连接是一项耗时的操作。所以你实际上想避免经常这样做;保持连接打开是实现这一目标的一种方式。

在服务器端应用程序中,当您尝试为来自多个用户的请求提供服务时,只有一个连接会产生瓶颈。在这种情况下,应该使用连接池(应用程序服务器将提供此功能)。在客户端应用程序(如JavaFX应用程序)中,在典型使用中,连接仅用于响应单个用户的操作,因此重用单个连接是一种合理的方法。