Connection timeout for DriverManager getConnection

遇到一個神奇的問題,遇到遠端的資料庫不穩定時,會讓我們的系統跟著遭秧,解法是設定看看 login timeout.


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.


 

Sample:

  private static Connection getHSQLConnection() throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://192.168.1.1:3306/MaxDB";

    DriverManager.setLoginTimeout(60); // fail after 60 seconds

    return DriverManager.getConnection(url, "sa", "");
  }

 

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *