4

What is the difference between isClose() method and isValid() method in Connection interface? http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html

What does it mean by invalid connection?

Does it mean connection is open and is not valid?

What happens when connection is not valid?

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
Charychap
  • 69
  • 1
  • 7
  • Check out http://stackoverflow.com/questions/7764671/java-jdbc-connection-status –  Feb 17 '15 at 09:53

2 Answers2

5

The Javadoc is clear enough.

isClose() is only guaranteed to return true if the connection was closed by a call to Connection.close(). If the connection was closed due to some errors, isClose() will not necessarily return true. Therefore, if it returns true, you can be sure the connection is closed, but if it returns false, you can't be sure.

isValid() does the opposite of isClose(). It attempts to do a positive check that the connection is still open, by running a database query. If it returns true, you know for sure the connection is open. If it returns false, you can't be sure if it's open or not (since the query may be delayed due to some network issues, which prevent it from completing before the given timeout).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • so is valid means is open right? is there is there any other way to be sure if the connection is valid (or open )??? – Charychap Feb 17 '15 at 10:10
  • @Charychap Yes, if isValid() returns true, it means open, but even if isValid() returns false, it may still be open. – Eran Feb 17 '15 at 10:11
  • Thanks for your answer. is there is there any other way to be sure if the connection is valid (or open )??? – Charychap Feb 17 '15 at 10:21
  • @Charychap You can always attempt to run a DB query or update and if it works, the connection must be open and valid. – Eran Feb 17 '15 at 10:24
0

isClosed() :- If we call close() on connection or any fatal errors occurred over connection then it's return true. So you have to create new connection for your code.

isValid(int timeout) :- In this case 1st it check for close if it not close then driver submit a query on the connection to test it's working or not. If it's valid then return true or false.

Janny
  • 681
  • 1
  • 8
  • 33