DBCP连接池

DBCP也是一个开源的连接池,是Apache Common成员之一,在企业开发中也比较常见,Tomcat内置连接池

1、导入jar:两个

2、配置文件

  1. 配置文件名称:*.properties
  2. 配置文件的位置:任意,建议src(classpath/类路径)
  3. 配置文件内容:properties不能编写中文,不支持在STS中修改,必须使用记事本修改内容,否则中文注释就乱码了

3、常见配置项:

http://commons.apache.org/proper/commons-dbcp/configuration.html

 

例子:

public class TestDBCP {

	private static DataSource dataSource;
	
	static {
		
		try {
			//1、加载配置文件,获得输入流
			InputStream is = TestDBCP.class.getClassLoader().getResourceAsStream("db2.properties");
			//2、用Properties对象处理输入流
			Properties pro = new Properties();
			pro.load(is);
			//3、创建连接池
			dataSource = BasicDataSourceFactory.createDataSource(pro);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public DataSource getDataSource() {
		return dataSource;
	}
	
	public Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}
	
	//测试
	@Test
	public void Test() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		TestDBCP pool = new TestDBCP();
		conn = getConnection();
		String sql = "select * from student";
		try {
			ps = conn.prepareStatement(sql);
			res = ps.executeQuery();
			while(res.next()) {
				System.out.println(res.getString(1)+"\t"+res.getString(2)+"\t"+res.getString(3));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值