Skip to Main Content
  • Questions
  • "Best" query for testing a connection

Breadcrumb

Question and Answer

Tom Kyte

Thanks for the question, Jerry.

Asked: February 27, 2004 - 8:11 pm UTC

Last updated: February 28, 2004 - 2:41 pm UTC

Version: 9,2,0

Viewed 1000+ times

You Asked

Our application uses a jdbc connection pool. We use the option to have the connection tested before being returned to us. We are currently using a simple query against dual:

select 1 from dual;

Is there a "better" query to use? (I'd really like to use "values 1".)


and Tom said...

why "test the connection" at all? just use it? in the event of an error -- fix it.

You have to do that anyway, consider:


a) grab connection
b) "test connection"
c) use connection but connection fails cause after you tested but before you
used it something went wrong.

testing a connection is a utter waste of time... but if you persist, insist, feel you must just:


"begin ? := 1; end;"

don't query, just run a small piece of plsql -- but again, it is a waste of CPU cycles as it proves "nothing" other than at the particular point in time you touched the connection, it worked. It doesn't mean or imply "it will continue to work" so you need error handling anyhow.






Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Why we test the connection

Jerry Brenner, February 28, 2004 - 2:34 pm UTC

We're using an open source connection pool implementation and we're relying on that implementation to return us a valid connection. The connection pool will test the connection before returning it to us. If it is bad, then it will toss that connection and try another one. If there is some major problem, like the database is down, then an exception will be thrown and reported out to the user.

Here's a situation that testing the connection solves:

Connection pool has N connections.
Something bad happens to the network or the database and the problem is fixed.
A user connects to our application. We get an invalid connection back from the connection pool because of the problem mentioned above. At this point, the only way to clean the connection pool is to restart the application. If the connection pool does the testing, then it discovers that the connection is bad (and all others are bad). It throws away the bad connections and gets a new valid connection to return.

Tom Kyte
February 28, 2004 - 2:41 pm UTC

the application can take care of "something bad happens to connection" just as easily by

a) asking for it
b) trying to use it
c) upon failure getting another

I've seen systems where much of their resources were spent "testing these connections" needlessly.

but, sigh, if you persist, just begin ?:=1; end; or even just execute "begin null; end;" and check the return code from the execute.