JDBC C3P0连接池和DBCP连接池

C3P0

开源免费的连接池,使用的开源项目有Spring,Hibernate等。需要导入jar包,配置文件为c3p0-config.xml

提供核心工具类:ComboPooledDataSource ,如果使用连接池必须创建该类的实例对象。 构造方法中放入"配置命名"。

编写工具类

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {
	private static DataSource dataSource = new ComboPooledDataSource("Cai");
	public static DataSource getDataSource(){
		return dataSource;
	}
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e); 
		}
	}
}

检测

public class Test_C3P0 {

	@Test
	public void test123(){
		Statement st = null;
		PreparedStatement pstmt = null;
		Connection conn =null;
	
		//不抽取工具类时需要新建如下对象中的一个
		//DataSource dataSource = new ComboPooledDataSource();
		//DataSource dataSource = new ComboPooledDataSource("Cai");
		try {
			conn=C3P0Utils.getConnection();
			st = conn.createStatement();	//调用了conn的方法 需要在实现类中重写方法
			//添加:
			int r = st.executeUpdate("insert into product values(null,'王1',200,null,3)");
			System.out.println(r);	
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			JdbcUtils.release(null, pstmt, conn);	
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}


DBCP连接池

需要导入jar包,配置文件后缀properties,不支持XML。创建连接的时候比较麻烦。

工具类

public class DBCPUtils {
	private static DataSource dataSource;
	static{
		try {
			//1 加载找到配置文件
			InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
			//2 加载输入流
			Properties props = new Properties();
			props.load(is);
			//3 创建数据源
			dataSource = BasicDataSourceFactory.createDataSource(props);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static DataSource getDataSource(){
		return dataSource;
	}
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值