Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically checking for open connection in JDBC

Tags:

java

oracle

jdbc

How do I check for an open connection in jdbc for oracle database?

Note: conn.isClosed() cannot be used for this.

like image 873
Chaitanya MSV Avatar asked Nov 08 '08 15:11

Chaitanya MSV


People also ask

How do I know if my JDBC connection is successful?

First, it submits a validation query to the database. Second, it uses the timeout parameter as a threshold for the operation. Finally, the connection is marked as valid if the operation succeeds within the timeout.

How do I keep my JDBC connection alive?

Set system parameters to keep JDBC driver connection alive. To keep the connection alive CDC can periodically select from the database in the control channel thread on the target.


2 Answers

Something like:

Statement stmt = null;
ResultSet rs =null;
try {
   stmt = conn.createStatement();
   // oracle
   rs = stmt.executeQuery("SELECT 1 FROM Dual");
   // others
   // rs = stmt.executeQuery("SELECT 1");
   if (rs.next())
      return true; // connection is valid
}
catch (SQLException e) {
   // TODO : log the exception ...
   return false;
}
finally {
   if (stmt != null) stmt.close();
   if (rs != null) rs.close();
} 

Note that if the connection is coming from a Connection Pool (in a Application Server for example) then the Pool may have a mechanism to check if a connection is valid or not. With BEA, you specify the SELECT in the "test-on-reserve" property.

If you are developing your own pool then you may want to take a look at how others are doing it (ex. Proxool).

like image 87
RealHowTo Avatar answered Sep 20 '22 23:09

RealHowTo


Usually a Connection Pool will also use the Connection.isClosed() method to check if the Connection is still valid. The problem is that not all JDBC drivers will handle this call correctly. So I assume that there are some simple check statements just like RealHowTo said. For Oracle he already mentioned the "SELECT 1 FROM Dual" which should succeed always for Oracle databases. I think that there are similar queries for the different database. I can remember that in a previous project we also implemented an own Connection Pool which used such validation queries.

like image 25
reallyinsane Avatar answered Sep 20 '22 23:09

reallyinsane