0

As I know connection is kind of very expensive operation. Which approach should I follow to handle few connections? I have seen a lots of examples where author talks about only one connection or uses connection pool(from JBoss or something). My code looks like this:

1) make new connection

2) do some logic

3) close connection

DriverManager.registerDriver(new net.sourceforge.jtds.jdbc.Driver());    
con = DriverManager.getConnection(URL, username, password);  
if(con!=null) 
   System.out.println("Connection Successful !\n");  
//logic      
if(con!=null)
   con.close();

But I've got few similar methods based on this approach. So do I really have to make new connection or should I use the only one? If I use one connection, do I need to close it after?

PS. App is not a servlet.

Tony
  • 3,605
  • 14
  • 52
  • 84
  • though it depends on how the application is deployed, Connection Pools are almost always better than manually managing connections. How is your application deployed? Is it a standalome application? – Nivas Jun 16 '14 at 13:01
  • My app is an OS service. – Tony Jun 16 '14 at 13:02
  • 1
    possible duplicate of [java - DataSource for standalone application - no application server](http://stackoverflow.com/questions/15588449/java-datasource-for-standalone-application-no-application-server) – Pablo Lozano Jun 16 '14 at 13:04

1 Answers1

3

You can use a connection pool like http://sourceforge.net/projects/c3p0/ or http://jolbox.com/ to abstract from this problem.

If you do not close connections after use, you will have lots of opening connections that are not in use (until database cleans up).

pringi
  • 3,987
  • 5
  • 35
  • 45