I am working on a JavaFX project that connects to a MySQL database (and as such I use a JDBC [java.sql] to perform various tasks from java to SQL). I've recently come into a lot of confusion regarding the standard procedure of connecting to a database.
From what I understand, I should create one instance of a Connection object, then I should pass this instance around the project until the end of the entire program.
Connection connection = DriverManager.getConnection(url, username, password);
If the statement above is true then I only need to call the previous line once in the entire program and pass the connection variable around the entire program whenever I need to connect to the database. If this is true, how can I pass around this instance of connection from one controller class to another?
Furthermore, I am seeing that it is a standard procedure (in order to maximize GUI responsiveness) to push all "costly" procedures onto another thread (not the main one that is handling the GUI) using the javafx.concurrencies library. If this statement is true, is it also true that I should push all methods that interact with the database into say a Task<V>
class?
Up until now, I created multiple object classes that each communicate with the database. In addition, I created a Database class that allows me to initialize a "new" connection to the database. For example,
public class Database {
public static Connection createConnectionToDB() throws SQLException{
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
}
Now in the various object classes, when I need to add, update, or delete some data from the database, I created an add, update, and delete method in each object to handle that object's data in the database. However, for each method, I thought (from my natural naivete) that it would be standard to first create a connection to the database via the previous Connection connection = createConnectionToDB()
method in the Database class then to use this connection instance to do what needs to be done, then close the connection with the connection.close()
method.
For example,
public class Object{
add(){
Connection connection = Database.createConnectionToDB();
PreparedStatement statement = ...
// some other lines
connection.close();
}
update(){
Connection connection = Database.createConnectionToDB();
PreparedStatement statement = ...
// some other lines
connection.close();
}
delete(){
Connection connection = Database.createConnectionToDB();
PreparedStatement statement = ...
// some other lines
connection.close();
}
}
That is, for each object, and each method for each object, a new connection is created and closed. Is this bad practice?