什么是validationQuery?

来源:互联网 发布:密室逃脱 网络宣传语 编辑:程序博客网 时间:2024/06/05 15:40

validationQuery是用来验证数据库连接的查询语句,这个查询语句必须是至少返回一条数据的SELECT语句。每种数据库都有各自的验证语句,下表中收集了几种常见数据库的validationQuery。

DataBasevalidationQueryhsqldbselect 1 from INFORMATION_SCHEMA.SYSTEM_USERSOracleselect 1 from dualDB2select 1 from sysibm.sysdummy1MySqlselect 1Microsoft SqlServerselect1postgresqlselect version()ingresselect 1derbyvalues 1H2select 1
如果你想支持多种数据库,你可以根据JDBC驱动来获取validationQuery,这里有个简单的类,根据JDBC驱动名称来获取validationQuery

import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class ValidationQuery {    public String getValidationQuery(String driver) {        Properties properties = loadProperties();        return properties.getProperty(driver, "");    }    private Properties loadProperties() {        String propertyFilename = "db.validation.properties";        try {            Properties props = new Properties();            InputStream resourceAsStream = this.getClass().            getClassLoader().getResourceAsStream(propertyFilename);            props.load(resourceAsStream);            resourceAsStream.close();            return props;        } catch (IOException e) {            throw new RuntimeException("Cannot load properties file '" + propertyFilename + "'.", e);        }    }    //Example: Get validationQuery for hsqldb    public static void main(String[] args) {        System.out.println(new ValidationQuery().getValidationQuery("org.hsqldb.jdbcDriver"));    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

创建“db.validation.properties”文件,并放置在classpath目录下

#hsqldborg.hsqldb.jdbcDriver=select 1 from INFORMATION_SCHEMA.SYSTEM_USERS#Oracleoracle.jdbc.driver.OracleDriver=select 1 from dual#DB2com.ibm.db2.jcc.DB2Driver=select 1 from sysibm.sysdummy1#mysqlcom.mysql.jdbc.Driver=select 1org.gjt.mm.mysql.Driver=select 1#microsoft sqlcom.microsoft.sqlserver.jdbc.SQLServerDriver=select 1#postgresqlorg.postgresql.Driver=select version();#ingrescom.ingres.jdbc.IngresDriver=select 1#derbyorg.apache.derby.jdbc.ClientDriver=values 1#H2org.h2.Driver=select 1




0 0
原创粉丝点击