48

I am (successfully) connecting to a database using the following:

java.sql.Connection connect = DriverManager.getConnection(
  "jdbc:mysql://localhost/some_database?user=some_user&password=some_password");

What should I be checking to see if the connection is still open and up after some time?
I was hoping for something like connect.isConnected(); available for me to use.

7 Answers 7

60

UPDATE

Oh, I just saw there is a new method available since 1.6:

java.sql.Connection.isValid(int timeoutSeconds):

Returns true if the connection has not been closed and is still valid. The driver shall submit a query on the connection or use some other mechanism that positively verifies the connection is still valid when this method is called. The query submitted by the driver to validate the connection shall be executed in the context of the current transaction.


ORIGINAL ANSWER

Your best chance is to just perform a simple query against one table, e.g.:

select 1 from SOME_TABLE;
1
  • 1
    postgresql jdbc executes "select 1", for the record.
    – rogerdpack
    Commented Jun 16, 2015 at 20:25
36

Nothing. Just execute your query. If the connection has died, either your JDBC driver will reconnect (if it supports it, and you enabled it in your connection string--most don't support it) or else you'll get an exception.

If you check the connection is up, it might fall over before you actually execute your query, so you gain absolutely nothing by checking.

That said, a lot of connection pools validate a connection by doing something like SELECT 1 before handing connections out. But this is nothing more than just executing a query, so you might just as well execute your business query.

1
  • 2
    There's some definite gain in testing the connection before using it (especially if it's a long lived connection and the underlying network might have used it). But this is also accurate in that you still need to handle errors in your own code since it might go down anytime.
    – rogerdpack
    Commented Jun 30, 2015 at 17:21
16

Use Connection.isClosed() function.

The JavaDoc states:

Retrieves whether this Connection object has been closed. A connection is closed if the method close has been called on it or if certain fatal errors have occurred. This method is guaranteed to return true only when it is called after the method Connection.close has been called.

4
  • 5
    As the javadoc says this will not give a valid answer in this case. It will only tell whether close() has been called or not.
    – Adam Arold
    Commented Apr 9, 2014 at 15:49
  • 4
    OK after some experimentation with the Postgres JDBC driver (at least), basically, if the underlying connection "is lost," isClosed() will still return true. However, when you use the connection, and it raises any exception, after that point, isClosed() will now return true. So basically you can "get away" with using isClosed (and avoid the latency of an extra call to isValid()) if you can somehow afford an an interrupted query here or there. Other than that isValid() is a good way to test, but requires an extra round trip time.
    – rogerdpack
    Commented Jun 16, 2015 at 20:24
  • 3
    Not sure why this has upvotes, this part of the Javadoc was omitted from the answer: This method generally cannot be called to determine whether a connection to a database is valid or invalid. A typical client can determine that a connection is invalid by catching any exceptions that might be thrown when an operation is attempted.
    – heez
    Commented Jan 7, 2019 at 20:58
  • Sounds like isClosed() || !isValid() is the way to go, allowing you to avoid the latency of isValid when possible but without sacrificing correctness.
    – Jake
    Commented Nov 7, 2023 at 15:28
12

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}
2
  • 8
    Should be, if(con!=null || !con.isClosed()) so that your check is on the object first, if it's null it will not continue with the validation of the IF statement. Your's will throw an exceptions because con might be NULL. Then you don't need the whole try catch at all.
    – user1853517
    Commented May 24, 2017 at 12:45
  • 1
    Or you can just do return con != null && !con.isClosed(). Commented Jun 19, 2019 at 13:53
4

If you are using MySQL

public static boolean isDbConnected() {
    final String CHECK_SQL_QUERY = "SELECT 1";
    boolean isConnected = false;
    try {
        final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
        isConnected = true;
    } catch (SQLException | NullPointerException e) {
        // handle SQL error here!
    }
    return isConnected;
}

I have not tested with other databases. Hope this is helpful.

5
  • Where does db come from? Commented Jun 17, 2015 at 12:05
  • See in the question connect variable it is db whatever you name it. Commented Jun 17, 2015 at 14:29
  • Then you may want to close your PreparedStatement to prevent memory leaks Commented Jun 17, 2015 at 15:26
  • @MonoThreaded, do whatever you like, it is just example. I am not writing real app here! Commented Jun 17, 2015 at 16:02
  • 1
    If you call the isValid(int timeoutSeconds) method instead, you basically get this behavior, but with a timeout to boot :)
    – rogerdpack
    Commented Jun 30, 2015 at 17:19
1

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}
0

Here is a simple solution if you are using JDBC to get the default connection

 private Connection getDefaultConnection() throws SQLException, ApiException {
    Connection connection = null;
    try {
         connection = dataSource.getConnection ();
    }catch (SQLServerException sqlException) {
        // DB_UNAVAILABLE EXCEPTION
    }
    return connection;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.