JDBC DriverManager 在尝试连接到数据库之前检测用户是否在网络上?

JDBC DriverManager detect if the user is on the network before trying to connect to the database?

我正在开发一个 Java 应用程序,它可以连接到我的办公室网络也可以不使用。

我的问题是,当用户未连接时,DriverManager.getConnection() 最多需要 20 秒才能最终释放它无法连接到数据库。

连接我或不连接服务器的代码:

public static Connection getConnection() {
    try{
        //cnx is my Connection object
        if(cnx ==null || cnx.isClosed()){
            Class.forName("com.mysql.jdbc.Driver");

            //Get the connection if possible
            cnx = DriverManager.getConnection(connectionString, user, password);
        }
        /*
        Basically, I'm just checking if "ConfigUser.isConnected()" is true
        later in the code to know if I should try to execute SQL queries
        */
        ConfigUser.setConnected(true);
        return cnx;
    }
    catch (Exception e){
    }
    ConfigUser.setConnected(false);
    return null;
}

我尝试使用 DriverManager.setLoginTimeout() 函数,但它似乎没有任何改变。

添加到 connectionString connect timeout in milliseconds:

&connectTimeout=5000

connectTimeout

Timeout for socket connect (in milliseconds), with 0 being no timeout. Only works on JDK-1.4 or newer. Defaults to '0'.