I am (successfully) connecting to a database using the following:
java.sql.Connection connect = DriverManager.getConnection(
\"jdbc:mysql://localhost/some_
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 returntrue
only when it is called after the method Connection.close has been called.
You also can use
public boolean isDbConnected(con Connection) {
//final String CHECK_SQL_QUERY = "SELECT 1";
try {
if(!con.isClosed() || con!=null){
return true;
}
} catch (SQLException e) {
return false;
}
return false;
}
Your best chance is to just perform a simple query against one table, e.g.:
select 1 from SOME_TABLE;
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.
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.
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");
}
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.