19 DBCP使用

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载,博客地址:http://blog.csdn.net/xpala https://blog.csdn.net/xpala/article/details/89051577

使用步骤:

> 添加jar包  commons-dbcp-1.4.jar  commons-pool-1.5.6.jar

> 添加属性资源文件

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/paper
username=root
password=123456

#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000


#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] 
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=utf8

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=REPEATABLE_READ

编写数据源工具类 

DataSource 为 javax.sql

public class DBCPUtils {
	
	private static DataSource ds=null;
	
	static{
		Properties p = new Properties();
		try {
			p.load(DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties"));
			try {
				ds=BasicDataSourceFactory.createDataSource(p);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() throws Exception{
		return ds.getConnection();
	}

猜你喜欢

转载自blog.csdn.net/xpala/article/details/89051577
19