DBCP数据源

java中的DBCP数据源,与c3p0数据源类似,需要读取的配置文件dbcpconfig.properties

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

#<!-- 初始化连接 -->
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=READ_COMMITTED
Dbutils.java

//需要导入的jar包:commons-dbcp-1.2.2.jar,commons-pool-1.3.jar
public class JdbcUtils {
	
	private static DataSource ds = null;	//数据源
	static{
		try{
			InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");	//读取数据库的配置文件,在classpath下
			Properties prop = new Properties();
			prop.load(in);	//加载dbconfig.properties文件
			BasicDataSourceFactory factory = new BasicDataSourceFactory();
			ds = factory.createDataSource(prop);	//返回数据源
		}catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static Connection getConnection() throws SQLException{
		return ds.getConnection();	//从连接池返回一个链接
	}
	
	public static void release(Connection conn,Statement st,ResultSet rs){	//释放数据库的链接
		
		if(rs!=null){
			try{
				rs.close();   //ds.getConnection()返回的connection一定对原生的connection中的close方法增强处理,
								//将数据库链接资源归还到连接池而不是归还给数据库
			}catch (Exception e) {
				e.printStackTrace();
			}
			rs = null;
		}
		if(st!=null){
			try{
				st.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
			st = null;
		}
		if(conn!=null){
			try{
				conn.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}	
}	
test.java

//测试方法
	public static void update(String sql,Object params[]) throws SQLException{
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		String sql = "";
		try{
			conn = getConnection();	//得到的是从连接池获得的链接,ds.getConnection();
			st = conn.prepareStatement(sql);
			
			st.executeUpdate();
		}finally{
			release(conn, st, rs);	//将数据库链接资源归还到连接池而不是归还给数据库
		}
	}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章