Here is my problem: I know it's not considered as a good pracitse, however I've been told by teacher to use singleton for JDBC connection.
Argument for why was that database connection is very expensive operation so I shouldn't connect to database every time I need to do operation with my database.
But how can I close the connection if my code looks like this? What are the options? I was looking for a solution of my problem but I couldn't find one.
Thank you very much! I really appreaciate all your time and effort.
public class DbConnect { public static Connection con; public static Statement st; public static ResultSet rs; public DbConnect() throws SQLException{ con = getDbConnection(); st = con.createStatement(); rs = null; } public static Connection getDbConnection(){ try{ Class.forName(("com.mysql.cj.jdbc.Driver")); con = DriverManager.getConnection( .... .... } public static void closeConnection() throws SQLException{ con.close(); st.close(); rs.close(); } // Example of how I use it:
public void removeCustomer(String value) throws SQLException{ String query="DELETE FROM customer WHERE idCustomer="+value; pst=DbConnect.con.prepareStatement(query); // THIS try { pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(CustomerRemover.class.getName()).log(Level.SEVERE, null, ex); } finally { pst.close(); } }