Connection timeout for DriverManager getConnection

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

You can set the Timeout on the DriverManager like this:

 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.



  private static Connection getHSQLConnection() throws Exception {
    String url = "jdbc:mysql://";

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

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



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