Efficient SQL test query or validation query that will work across all (or most) databases
Many database connection pooling libraries provide the ability to test their SQL connections for idleness. For example, the JDBC pooling library c3p0 has a property called preferredTestQuery
, which gets executed on the connection at configured intervals. Similarly, Apache Commons DBCP has validationQuery
.
Many example queries I've seen are for MySQL and recommend using SELECT 1;
开发者_如何学编程 as the value for the test query. However, this query doesn't work on some databases (e.g. HSQLDB, for which SELECT 1
expects a FROM
clause).
Is there a database-agnostic query that's equivalently efficient but will work for all SQL databases?
Edit:
If there's not (which seems to be the case), can somebody suggest a set of SQL queries that will work for various database providers? My intention would be to programmatically determine a statement I can use based on my database provider configuration.
After a little bit of research along with help from some of the answers here:
SELECT 1
- H2
- MySQL
- Microsoft SQL Server (according to NimChimpsky)
- PostgreSQL
- SQLite
- Hive
SELECT 1 FROM DUAL
- Oracle
SELECT 1 FROM any_existing_table WHERE 1=0
or
SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS
or
CALL NOW()
HSQLDB (tested with version 1.8.0.10)
Note: I tried using a
WHERE 1=0
clause on the second query, but it didn't work as a value for Apache Commons DBCP'svalidationQuery
, since the query doesn't return any rows
VALUES 1
or SELECT 1 FROM SYSIBM.SYSDUMMY1
- Apache Derby (via daiscog)
SELECT 1 FROM SYSIBM.SYSDUMMY1
- DB2
select count(*) from systables
- Informix
If your driver is JDBC 4 compliant, there is no need for a dedicated query to test connections. Instead, there is Connection.isValid to test the connection.
JDBC 4 is part of Java 6 from 2006 and you driver should support this by now!
Famous connection pools, like HikariCP, still have a config parameter for specifying a test query but strongly discourage to use it:
精彩评论