Zilvinas
Zilvinas

Reputation: 262

JDBC detect a lost connection

How would you detect a lost connection using JDBC in a reliable and an efficient way? Currently I'm using a Vertica JDBC driver. I don't think I can use connection pools as I need to control to which node I'm connected at all times. Things I thought of so far:

  1. Assume SQLException is a lost connection. Seems unreliable.
  2. Check ex.getCause and look for a socket exception. Not sure if checking cause is a good practice.
  3. Check error code which I know is a case for a lost connection. Also seems a bit unreliable.

Edit: I've tried isValid and isClosed. isValid throws an exception and isClosed always returns false regardless.

Upvotes: 1

Views: 2038

Answers (1)

Katona
Katona

Reputation: 4901

From version 1.6, you can theoretically use the Connection.isValid method but I am not sure if every vendor supports it. An other alternative is using a connection pool which manages connections and you get the connection from them and release it when you don't need it. Connection pools take the responsiblity of maintaining connections and they always provide valid connections.

Upvotes: 1

Related Questions