Skip to main content
1 of 2
Sleiman Jneidi
  • 3.2k
  • 11
  • 20

You could use a Pooling Data Source to reuse the same connection if there is an opened one.

   InitialContext ctx = new InitialContext();
   DataSource ds =(DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
   Connection connection = null;
   try {
        connection = ds.getConnection();
       //...
   }finally{
    try{
     if(null != connection){
     connection.close();
     }
    }catch(Exception ex){ // use a more specific exception
      // logging
    }
   }

Moreover, use Prepared Statement instead of Statements, it gives automatic prevention of SQL injection attacks.

Use proper logging instead of printStackTrace

Sleiman Jneidi
  • 3.2k
  • 11
  • 20