开源数据源之二——C3P0

来源:互联网 发布:java面对对象 编辑:程序博客网 时间:2024/06/06 05:15

前面已经讲过数据库连接池的处,以及开源数据源之一DBCP。现在我们讲一下另外一种开源数据源C3P0。

C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring。


C3P0依赖包:c3p0-0.9.5.1.jar     mchange-commons-java-0.2.10

下载地址:http://download.csdn.net/download/xzp_12345/9990801


C3P0开发步骤(二步):

第一步(重点):配置C3P0

连接池C3P0的配置有三种方法:

1. 编写java代码,在Util中使用set方法进行配置(不推荐)

2. 编写properties配置文件(在这里也不推荐使用,DBCP使用的就是这种方法)

3. 编写XML配置文件c3p0-config.xml

注:参考文件中的【doc】下的index.xml开发文档:http://download.csdn.net/download/xzp_12345/9990801

       首先,先简单介绍一下第一种方法

编写C3P0Util工具类:

public class C3P0Util {private static ComboPooledDataSource dataSource = new ComboPooledDataSource();static {try {/** * Java代码使用set方法进行C3P0配置 */dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/day15");dataSource.setUser("root");dataSource.setPassword("123456");dataSource.setMinPoolSize(10);dataSource.setAcquireIncrement(5);dataSource.setMaxPoolSize(50);} catch (Exception e) {throw new ExceptionInInitializerError("C0P3配置信息错误!");}}public static DataSource getDataSource() {return dataSource;}public static Connection getConnection() {try {return dataSource.getConnection();} catch (SQLException e) {throw new RuntimeException("数据库连接错误!");}}}

第三种方法:xml配置。配置文件必须是c3p0-config.xml(可参考下载文件中的index.xml文档)


配置:

<?xml version="1.0" encoding="UTF-8"?><c3p0-config>  <default-config>    <property name="driverClass">com.mysql.jdbc.Driver</property>    <property name="jdbcUrl">jdbc:mysql://localhost:3306/day15</property>    <property name="user">root</property>    <property name="password">123456</property>    <property name="initialPoolSize">10</property>    <property name="maxIdleTime">30</property>    <property name="maxPoolSize">100</property>    <property name="minPoolSize">10</property>    <property name="maxStatements">200</property>  </default-config></c3p0-config>

利用xml配置的话,在C3P0Util中就没有了下面的代码(所以说更简便)



第二步:调用这个连接池

import java.sql.Connection;import java.sql.SQLException;import com.yangguang.c3p0.util.C3P0Util;import com.yangguang.dbcp.util.DBCPUtil;public class Test {public static void main(String[] args) {Connection connection = C3P0Util.getConnection();System.out.println("The Class is:"+connection.getClass().getName());try {connection.close();//放回连接池} catch (SQLException e) {e.printStackTrace();}}}


阅读全文
0 0
原创粉丝点击