版本:c3p0-0.9.2.1
代码长度:382
官方文档出处:http://www.mchange.com/projects/c3p0/ useing the datasources factory class
我们先从一个简单的例子来了解这个类
package test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
public class testUnpooledDatasource {
public static void main(String[] argv) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
DataSource ds_unpooled = DataSources.unpooledDataSource(
"jdbc:oracle:thin:@10.185.15.183:1521:gxmc2", "gxpm5",
"gxpm5");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = ds_unpooled.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery("select count(*) from bo_designone ");
while (rs.next())
System.out.println(rs.getString(1));
} finally {
attemptClose(rs);
attemptClose(stmt);
attemptClose(con);
}
} catch (Exception e) {
e.printStackTrace();
}
}
static void attemptClose(ResultSet o) {
try {
if (o != null)
o.close();
} catch (Exception e) {
e.printStackTrace();
}
}
static void attemptClose(Statement o) {
try {
if (o != null)
o.close();
} catch (Exception e) {
e.printStackTrace();
}
}
static void attemptClose(Connection o) {
try {
if (o != null)
o.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void UsePoolBackedDataSource() {
}
}
DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/testdb", "swaldman", "test-password");
直接获取了jdbc数据源
DataSource ds_pooled = DataSources.pooledDataSource( ds_unpooled )
再把他转成 有连接池的数据源
后台在处理的时候用到了关键类
他继承了DriverManagerDataSourceBase 又实现了接口 DataSource
DriverManagerDataSource out = new DriverManagerDataSource();
new的时候创建DriverManagerDataSource 并使用C3P0Registry注册当前类,底层涉及到了Coalescer,c3p0自己维护的一个唯一值set ,用来做仓储用。
新建完了以后 绑定一个值变化的监听器,这个很有意思,大家不妨看一下DriverManagerDataSource的方法 setUpPropertyListeners
接着从配置文件里去取数据库的用户名和密码维护在自身的变量里。
然后就是常用的获取连接的操作了
最终的datasource 是进过这几部来到我们面前的
1DriverManagerDataSource打算new 一个自身出来,他就找到了他的父亲DriverManagerDataSourceBase ,父亲告诉他,你等着,我再生一个你出来,不过我还要到计生委那里给你弄个准生证和登记证明出来。
21DriverManagerDataSource拿到了这货,然后给他安装了个报警器setUpPropertyListeners,谁要是敢动他身上的driverClass,他就喊一句“你们不能摸的”,别人回去理解这话的意思的。
3然后他给他赋值了username password等一些东西。
然后他就光荣的宣布他有自己的儿子了,其实是他老爸的种。
con = ds_unpooled.getConnection();
就没有什么好说的了,就是DriverManager.getDriver( jdbcUrl ).connect( jdbcUrl, properties ); 而已
重点之一:如何管理driverclass的