C3P0数据源

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

c3p0与dbcp区别

dbcp没有自动回收空闲连接的功能

c3p0有自动回收空闲连接功能

方式一:

步骤:

1、加入jar

如果是c3p0-0.9.1.2版本,加入一个jar即可c3p0-0.9.1.2.jar

如果是c3p0-0.9.2之后的版本,需要加入两个jar:c3p0-0.9.X.jar和mchange-commons-java-XX.jar

2、编写代码

package com.jdbc.datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class TestC3P0 {

public static void main(String[] args)throws Exception {

//1、创建c3p0数据源对象

ComboPooledDataSource ds = new ComboPooledDataSource();

//2、设置属性

ds.setDriverClass( “com·mysql·jdbc·Driver” );

ds.setJdbcUrl( “jdbc:mysql://localhost:3306/test” );

ds.setUser(“root”);

ds.setPassword(“root”);

//3、获取链接

System.out.println(ds.getConnection());

}

}

方式二:

  1. 在src目录创建 c3p0-config.xml 文件, 参考帮助文档中 Appendix B: Configuation Files 的内容
  2. 创建 ComboPooledDataSource 实例;
  3. 在src目录创建 c3p0-config.xml 文件, 参考帮助文档中 Appendix B: Configuation Files 的内容
  4. 创建 ComboPooledDataSource 实例;

DataSource dataSource = new ComboPooledDataSource(“helloc3p0”);

  1. 从 DataSource 实例中获取数据库链接·

helloc3p0“>

root

root

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/test

5

5

5

10

package com.jdbc.datasource;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class TestC3P02 {

public static void main(String[] args)throws Exception {

DataSource dataSource = new ComboPooledDataSource(“helloc3p0“);

System.out.println(dataSource.getConnection());

}

}

ception;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3p0Utils {

//创建数据源,用的是c3p0-config.xml文件中

config>

private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

//获取数据源对象

public static ComboPooledDataSource getDataSource() {

return dataSource;

}

//获取链接

public static Connection getConnection() throws SQLException{

return dataSource.getConnection();

}

}

文章转载链接:http://www.atguigu.com/jsfx/13307.html