【问题标题】:Opening and closing Connection within JavaFX application在 JavaFX 应用程序中打开和关闭连接
【发布时间】:2015-04-06 20:26:13
【问题描述】:

我想编写一个在 MySQL 数据库上运行的小应用程序。 但是,在阅读了以下这两个主题后,我对使用 Connection to database 的正确方法感到困惑:

is it safe to keep database connections open for long time

Closing Database Connections in Java

一个说我应该长时间保持 Connection 而 Statements 简短,第二个说我应该尽快关闭所有内容。

哪种方式更好/合适?

示例 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);
    }
}

或者你知道更好的方法?

【问题讨论】:

    标签: mysql database-connection javafx-8


    【解决方案1】:

    您引用的两个问题之间没有矛盾。第一个说“可以长时间保持连接打开”。第二个说“完成连接后必须关闭连接”。因此,您可以根据需要将其保持打开状态,只要完成后将其关闭即可。你不能做的是重复打开新连接而不是关闭它们。

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

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

    【讨论】:

    • 我发现只有第一次连接服务器需要很长时间。当我再次这样做时,它会快得多。我现在在想,在第一个示例中使用代码会更好也更安全。
    • 听起来数据源实现正在为您缓存打开的连接。因此,当您第一次检索它时,它会打开它;当您“关闭”它(通过 try-with-resources 构造隐式)时,它会保持打开状态,但会再次将其标记为可用。然后对getConnection() 的后续调用花费更少的时间。它也可能正在为您实现一个池:我不熟悉MysqlDataSource
    • 如果您在需要时打开连接并在完成后将其丢弃,这实际上不会关闭连接,它只会将其返回到连接池中再次使用。在这里找到:link你认为它与java相同?
    • "With Java" 太笼统了。如果您从DriverManager 检索连接并在其上调用close,则绝对不是真的。如果您从实现连接池的DataSource 中检索它绝对是正确的(这实际上是“连接池”的意思。我不知道MysqlDataSource 是如何实现的(并且可以在快速搜索中找到好的文档),但假设这就是它正在做的事情似乎是合理的。
    • 非常感谢。单一连接方法改变了我的整个应用程序
    猜你喜欢
    • 1970-01-01
    • 2015-12-14
    • 2012-07-06
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多