【发布时间】: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