JDBC connection timeout

Wednesday, September 30, 2009
By Steve

While testing a remote data center today, we had some network connectivity issues. We twiddled our thumbs while waiting for connections to throw an exception due to a network block.

I found the setLoginTimeout() method on the DriverManager class. You can use it as show below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.sql.*;
 
public class checkConn {
  public static void main(String[] args) {
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      System.out.println(DriverManager.getLoginTimeout());
      DriverManager.setLoginTimeout(20);
      System.out.println(DriverManager.getLoginTimeout());
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@oh2xpwcdg01:2484/hidden.service.domain",
                                                    args[0],
                                                    args[1]);
      ResultSet rst = conn.createStatement().executeQuery("select sysdate, to_char ( sysdate, 'DD-MON-YYYY') from dual");
      if (rst.next()) {
        System.out.println(rst.getDate(1) + " " + rst.getString(1));
      }
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
}

Leave a Reply