JDBC connection timeout

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:

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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.