Connection timeout for DriverManager getConnection

kal picture kal · Nov 5, 2009 · Viewed 95.2k times · Source

I am trying to connect to DB using the standard JDBC way

connection = DriverManager.getConnection(url, username, password);

Is there a maximum value of timeout on the connection, how long does a connection live, can I increase the value. I want in cases the connection to be open forever , is it a good idea.

Answer

Vincent Ramdhanie picture Vincent Ramdhanie · Nov 5, 2009

You can set the Timeout on the DriverManager like this:

 DriverManager.setLoginTimeout(10);
 Connection c = DriverManager.getConnection(url, username, password);

Which would imply that if the connection cannot open within the given time that it times out.

In terms of keeping a connection open forever, it is possible if you do not close the connection but it may not be a good idea. Connections should be closed as soon as you are finished with them.

If you want to optimise the opening and closing of connections then you can use a connection pool.