DBCP has a connection validation query option - validationQuery
, according to the docs. You can set it to something like SELECT 1;
and DBCP will run that before returning a connection to test it.
That said, your app really should handle this case. SQL queries can fail for all sorts of reasons and you should always do your queries in a retry loop with a time back-off and retry limit, plus some logic to decide what exceptions are recoverable on retry and which aren't (use the SQLState for that).
In particular, validation is subject to a race condition where you can have event orderings like:
- Validate
- Pass connection to app
- Server shutdown
- App runs first statement
or
- Validate
- Pass connection to app
- App runs first statement, opening a transaction
- Server shutdown
- App runs second statement
... so it remains important for your app to have a proper retry loop and good transaction handling.
You can get the SQLState from the SQLException: SQLException.getSQLState
. The codes for PostgreSQL are in the PostgreSQL manual.
try-catch
to catch the exception (checkinge.getMessage()
for it having actually been a server restart), and then reconnect to the database from within thecatch
statement or another block of code triggered by it. – Vulcan Jun 4 '13 at 19:40SQLSTATE
you can get from thePSQLException
to check the cause of the issue. Otherwise you'll get fun problems when the message is reworded in a new version or someone's running Pg in a different language. – Craig Ringer Jun 4 '13 at 23:48PSQLException
had such a field (I've never used PSQL before). It should definitely be used instead of the message, you're right. – Vulcan Jun 4 '13 at 23:54getSQLState()
is an SQLException method, and is standard across all DBs. never parse the error message - for any DB, not just Pg. That's what the SQLState is for. The message classes are fairly standard, too. – Craig Ringer Jun 4 '13 at 23:55getSQLState()
. Thanks. – Vulcan Jun 4 '13 at 23:57