Reputation: 135
I was wondering whether I need a closeConnection() method in my DBConnecter class. I know that you would normally close your connection whenever you are done using it, but with the connection being a singleton I am not completely sure.
Here is my DBConnecter class:
public static String driver = "com.mysql.jdbc.Driver";
public static String URL = "jdbc:mysql://localhost/polygondb";
public static String ID = "root";
public static String PW = "root";
private static Connection connection = null;
public static Connection getConnection() {
if (connection == null) {
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connection = DriverManager.getConnection(URL, ID, PW);
} catch (SQLException ex) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
return connection;
}
It might not be such a big deal, but I want to make sure as it is a school project for the exam (:
Upvotes: 1
Views: 1840
Reputation: 2489
Opening up a connection to a database is an expensive process. Since you're using a singleton and assuming that all your database interactions are being handled by this object I would recommend keeping the connection alive. You will however want to close the connection prior to exiting the application.
If you are expecting many queries to occur at the same time you might want to look into connection pools, however since this is a school project I would assume that this isn't the case.
Upvotes: 2