JavaWeb学习-数据库连接池-3-DBCP数据源

前面我们写的自定义的连接池,其实以后学习开发中都不需要这么干,很多都别人写好了,只需要简单配置一下就好。这篇来学习DBCP框架,其实就是一个连接池。DBCP全称为Database Connection Pool,是apache开发提供的。

1.DBCP使用步骤

1.添加jar包,在tomcat安装路径的lib目录下commons-dbcp-xxx.jar 和commons-pool-xxx.jar
2.添加属性资源文件
3.编写数据源工具类

2.DBCP使用教程

2.1 新建一个Java 动态web项目,提取去maven仓库下载两个jar包,拷贝到如下图所示位置。

2.2属性资源文件

在src目录下创建一个dbconfig.properties文件,copy下面内容


driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/j2ee
username=root
password=123456

initialSize=10

maxActive=50

maxIdle=20

minIdle=5

maxWait=60000

connectionProperties=useUnicode=true;characterEncoding=utf8

defaultReadOnly=

defaultTransactionIsolation=REPEATABLE_READ

defaultAutoCommit=true

注意properties文件中不可以写中文注释,只能写英文,非要写中文,需要转成对应unicode码,一般不写中文,写了转成unicdoe码也看不懂。

2.3添加数据源工具类

package com.anthony.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPUtils {
	private static DataSource ds = null;
	
	static {
		Properties pro = new Properties();
		try {
			pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties"));
			ds = BasicDataSourceFactory.createDataSource(pro);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ExceptionInInitializerError("初始化错误,请检查配置文件");
		}
	}
	
	public static Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("服务器忙...");
		}
	}
	
	public void release(Connection conn, Statement stmt, ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null; //赶紧垃圾回收
		}
		if(stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			stmt = null;
		}
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
		}
	}

}

关于如何调用这个方法,就和我们前面调用DBUtils.java一样,换成这个DBCPUtils.java就行。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值