http://www.mchange.com/projects/c3p0/

c3p0的配置参数preferredTestQuery用于检测数据库连接测试,检测数据库是否能连接成功。

Default: null
Defines the query that will be executed for all connection tests, if the default ConnectionTester (or some other implementation of QueryConnectionTester, or better yet FullQueryConnectionTester) is being used.
Defining a preferredTestQuery that will execute quickly in your database may dramatically speed up Connection tests. (If no preferredTestQuery is set, the default ConnectionTester executes a getTables() call on the
Connection's DatabaseMetaData. Depending on your database, this may execute more slowly than a "normal" database query.) NOTE: The table against which your preferredTestQuery will be run must exist in the
database schema prior to your initialization of your DataSource. If your application defines its own schema, try automaticTestTable instead. [See "Configuring Connection Testing"]

与之对应的是参数:connectionTesterClassName,配置用于c3p0连接测试的实现类。

Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester
The fully qualified class-name of an implememtation of the ConnectionTester interface, or QueryConnectionTester if you would like instances to have access to a user-configured preferredTestQuery. This can be
used to customize how c3p0 DataSources test Connections, but with the introduction of automaticTestTable and preferredTestQuery configuration parameters, "rolling your own" should be overkill for most users.
[See "Configuring Connection Testing"]

connectionTesterClassName参数值必须实现接口:com.mchange.v2.c3p0.ConnectionTester,跟踪源码发现,其继承关系如下:

    - com.mchange.v2.c3p0.ConnectionTester
- com.mchange.v2.c3p0.QueryConnectionTester
- com.mchange.v2.c3p0.FullQueryConnectionTester
- com.mchange.v2.c3p0.UnifiedConnectionTester
- com.mchange.v2.c3p0.AbstractConnectionTester
- com.mchange.v2.c3p0.impl.DefaultConnectionTester

通常,我们都可能不会配置这2个参数,而是直接使用c3p0的默认配置。
那么,它们的默认值分别是什么呢?

com.mchange.v2.c3p0.impl.C3P0Defaults中定义了c3p0的默认参数配置,其中:

private final static ConnectionTester CONNECTION_TESTER = new DefaultConnectionTester();

显然,当没有明确定义参数connectionTesterClassName值时,c3p0默认使用的是com.mchange.v2.c3p0.impl.DefaultConnectionTester实现。
com.mchange.v2.c3p0.impl.DefaultConnectionTester定义如下方法:

public int activeCheckConnection(Connection c, String query, Throwable[] rootCauseOutParamHolder)
{
// if (Debug.DEBUG && Debug.TRACE == Debug.TRACE_MAX && logger.isLoggable( MLevel.FINER ) )
// logger.finer("Entering DefaultConnectionTester.activeCheckConnection(Connection c, String query). [query=" + query + "]"); if (query == null)
return activeCheckConnectionNoQuery( c, rootCauseOutParamHolder);
else
{
.....
}
}

当没有明确定义preferredTestQuery值时,c3p0执行如下查询:

private int activeCheckConnectionNoQuery(Connection c,  Throwable[] rootCauseOutParamHolder)
{
// if (Debug.DEBUG && Debug.TRACE == Debug.TRACE_MAX && logger.isLoggable( MLevel.FINER ) )
// logger.finer("Entering DefaultConnectionTester.activeCheckConnection(Connection c). [using default system-table query]"); ResultSet rs = null;
try
{
rs = c.getMetaData().getTables( null,
null,
"PROBABLYNOT",
new String[] {"TABLE"} );
return CONNECTION_IS_OKAY;
}
}

com.mysql.jdbc.DatabaseMetaData实现如下:

public java.sql.ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, final String[] types) throws SQLException {
...
try {
     // 执行sql语句,检测mysql是否可以连通
     results = stmt.executeQuery((!DatabaseMetaData.this.conn.versionMeetsMinimum(5, 0, 2) ? "SHOW TABLES FROM " : "SHOW FULL TABLES FROM ")
+ StringUtils.quoteIdentifier(catalogStr, DatabaseMetaData.this.quotedId, DatabaseMetaData.this.conn.getPedantic())
+ " LIKE " + StringUtils.quoteIdentifier(tableNamePat, "'", true));
} catch (SQLException sqlEx) {
if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE.equals(sqlEx.getSQLState())) { throw sqlEx; }
}
...
}

调试后发现,此时执行的sql语句为:SHOW FULL TABLES FROM `dbname` LIKE 'PROBABLYNOT'(dbname为实际数据库名称)即为preferredTestQuery参数的默认值。
执行该语句不返回任何记录,但是可以通过该语句检测mysql是否可以连通。

总结:
1. 通常不需要明确指定connectionTesterClassName参数,使用默认实现即可。
2. preferredTestQuery参数值最好明确配置,不要使用默认值。该参数通常配置为:"select 1" ,效率比"SHOW FULL TABLES FROM `dbname` LIKE 'PROBABLYNOT''高。

【参考】
http://josh-persistence.iteye.com/blog/2229929 深入浅出数据库连接池c3p0
https://stackoverflow.com/questions/30521146/how-configure-connection-existence-check-in-c3p0 How configure connection existence check in C3P0?

c3p0配置之preferredTestQuery参数默认值探秘的更多相关文章

  1. Python函数参数默认值的陷阱和原理深究"

    本文将介绍使用mutable对象作为Python函数参数默认值潜在的危害,以及其实现原理和设计目的 本博客已经迁移至: http://cenalulu.github.io/ 本篇博文已经迁移,阅读全文 ...

  2. java函数参数默认值

    java函数参数默认值 今天,需要设定java函数参数的默认值,发现按照其它语言中的方法行不通 java中似乎只能通过函数的重载来实现 函数参数默认代码

  3. struts2视频学习笔记 03-06(Struts 2配置文件无提示问题,Action配置中的各项默认值,各种转发类型)

    课时3 解决Struts 2配置文件无提示问题(eclipse):window→preference→XML→XML Catlog

  4. js定义参数默认值

    javascript可以用arguments定义参数组.   一.简单的定义参数默认值 function test1(a,b){ //如果有参数一,则返回参数一,如果没有返回默认值"这是参数 ...

  5. C#语法糖之第二篇: 参数默认值和命名参数 对象初始化器与集合初始化器

    今天继续写上一篇文章C#4.0语法糖之第二篇,在开始今天的文章之前感谢各位园友的支持,通过昨天写的文章,今天有很多园友们也提出了文章中的一些不足,再次感谢这些关心我的园友,在以后些文章的过程中不断的完 ...

  6. Ruby方法参数默认值的一个小技巧在Rails中的应用

    我们需要生成一个gravatar格式的html.image标示,于是写了如下方法: def gravatar_for(user) gravatar_id = Digest::MD5::hexdiges ...

  7. es6(三):es6中函数的扩展(参数默认值、rest参数、箭头函数)

    1.函数可以设置参数默认值 function test1(x,y=1){ console.log(x,y) } test1(10)//10 1 2.rest参数:形式为...变量名 function ...

  8. ES6参数默认值

    参数默认值 1.首先,来看一下es5中的函数默认值 var a = a || 10; var b = b || "none" // 当a的值或者b的值为undefined时,根据逻 ...

  9. C++ 函数的重载和参数默认值

    函数的重载和参数默认值视频教程 函数的重载注意事项: 只会根据三项内容进行重载:参数的个数.参数的类型.参数的顺序 参数默认值: 参数的默认值可以在函数的定义中也可以在函数的声明中,但不能同时有 从第 ...

随机推荐

  1. python实用脚本集

    iScript 是Github上 PeterDing 大神写的一个脚本集,由多数的 python 脚本和少数GM脚本组成. 含有以下几个脚本: xiami.py - 下载或播放高品质虾米音乐(xiam ...

  2. python装饰器中的计时器thd.strat用法

    thd = KThread(target=_new_func, args=(), kwargs=new_kwargs) thd.start() thd.join(seconds) alive = th ...

  3. hdu2795(线段树)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2795 题目大意:有一个h*w的公告牌,要在其上贴公告.现在有n个公告,每个公告的尺寸为1*wi,即高度 ...

  4. A1018. Public Bike Management

    There is a public bike service in Hangzhou City which provides great convenience to the tourists fro ...

  5. 回调函数: 一定要在函数名前加上 CALLBACK,否则有可能引起内存崩溃!

    今天又遇到一个莫名其妙的内存崩溃问题,问题代码 EnumChildWindows(...): EnumChildWindows(hwnd_panel_text_watermark, (WNDENUMP ...

  6. 第二十四节,TensorFlow下slim库函数的使用以及使用VGG网络进行预训练、迁移学习(附代码)

    在介绍这一节之前,需要你对slim模型库有一些基本了解,具体可以参考第二十二节,TensorFlow中的图片分类模型库slim的使用.数据集处理,这一节我们会详细介绍slim模型库下面的一些函数的使用 ...

  7. ElasticSearch6.5.0 【Rejecting mapping update to [posts] as the final mapping would have more than 1 type】

    今天想在一个Index上增加一个type,结果报错 java.lang.IllegalArgumentException: Rejecting mapping update to [posts] as ...

  8. echarts柱状图鼠标移动在柱状图上显示数据给数据添加单位

    解决问题: 关键代码如下: tooltip : { trigger: 'axis', formatter:function(params){ return params[0].name+"& ...

  9. FineUILearning

    一:表单控件的学习: 1(1) <f:PageManager > 将对象引用设置到对象的实例,否则页面无法显示: (2)<Menu></Menu>就是下拉菜单控件 ...

  10. C/S,B/S的应用的区别

    C/S和B/S都是软件架构方式: C/S(Client/Server) :客户端/服务器结构,其中客户端和服务器端都是独立的计算机,客户端是面向用户的应用程序或者是接口,服务器端通常采用高性能的PC. ...