0

I'm working on a Java app that can be used connected to my office network or not.

My problem is that, when the user is not connected, the DriverManager.getConnection() takes up to 20 seconds before finally releasing that it can't connect to the database.

Code that connect me or not to the server :

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;
}

I've tried to use the DriverManager.setLoginTimeout() function but it didn't seem to change anything.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Natty
  • 497
  • 1
  • 11
  • 23
  • Please check https://stackoverflow.com/questions/1683949/connection-timeout-for-drivermanager-getconnection – Sukhpal Singh Nov 05 '18 at 10:42
  • They are talking about the life of the connection, which is not my question – Natty Nov 05 '18 at 10:43
  • How are you connecting to your office network? Is it part of your application or is it a separate VPN application that the user has to start separately? – Robin Green Nov 05 '18 at 10:43
  • @NattyRoots You didn't follow complete post. Same solution as accepted by you. https://stackoverflow.com/questions/1683949/connection-timeout-for-drivermanager-getconnection/10764256#10764256 – Sukhpal Singh Nov 05 '18 at 10:55
  • @SukhpalSingh Indeed ! My bad, I assumed they were talking about something else after reading the accepted answer – Natty Nov 05 '18 at 10:57

1 Answers1

2

Add to 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'.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Well, I'll have to question my life's choices for not seeing that... Thanks man, works like a charm – Natty Nov 05 '18 at 10:54