package cn.itcast.datasource;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;
//我们以前那个连接池底层是JdbcUtils.getConnection(),那个就找配置文件
//BasicDataSource缺少连接数据库最基本的四个条件:驱动,url,username,password
public class DbcpTest { //1.手动配置
@Test
public void test1() throws SQLException{
//我们以前那个连接池底层是JdbcUtils.getConnection(),那个就找配置文件
BasicDataSource bds = new BasicDataSource();//BasicDataSource不会去找配置文件
//需要设置连接数据库最基本四个条件
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql:///day18");
bds.setUsername("root");
bds.setPassword("");
//得到一个Connection
Connection con = bds.getConnection();
ResultSet rs= con.createStatement().executeQuery("select * from account");
while(rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getString("name"));
} rs.close();
con.close();//将Connection对象重新装入到连接池.
//那连接池人家底层肯定实现了,肯定读这close方法进行功能增强了
//只要是连接池,Connection对象肯定放回去了,不是关 }
//2.自动配置
@Test
public void test2() throws Exception{ Properties props = new Properties();//差一个Properties对象,new一个呗
/*
props.setProperty("driverClassName", "com.mysql.jdbc.driver");//key值要查看BasicDataSourceFactory的源码里面的常量才知道
props.setProperty("url", "jdbc:mysql:///day18");//key值要查看BasicDataSourceFactory的源码里面的常量才知道
props.setProperty("username", "root");//key值要查看BasicDataSourceFactory的源码里面的常量才知道
props.setProperty("password", "");//key值要查看BasicDataSourceFactory的源码里面的常量才知道
*/ //Properties里面的东西可以直接从文件里面加载
//之所以为自动,是因为查看jdk文档知道Properties对象可以用文件流加载配置文件
FileInputStream fis = new FileInputStream("E:\\北风网\\day18_2\\src\\dbcp.properties");
props.load(fis);
DataSource ds = BasicDataSourceFactory.createDataSource(props);//createDataSource是静态方法
Connection con = ds.getConnection();
ResultSet rs= con.createStatement().executeQuery("select * from account");
while(rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getString("name"));
}
rs.close();
con.close();//人Connection最后关闭时还是把它放到连接池不会关不会销毁
} }
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day18
username=root
password= #driverClass=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:XE
#username=system
#password=system

BasicDataSoureFactory源码

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.apache.commons.dbcp; import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Collections; import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import javax.sql.DataSource; /**
* <p>JNDI object factory that creates an instance of
* <code>BasicDataSource</code> that has been configured based on the
* <code>RefAddr</code> values of the specified <code>Reference</code>,
* which must match the names and data types of the
* <code>BasicDataSource</code> bean properties.</p>
*
* @author Craig R. McClanahan
* @author Dirk Verbeeck
* @version $Revision: 828639 $ $Date: 2009-10-22 06:27:43 -0400 (Thu, 22 Oct 2009) $
*/
public class BasicDataSourceFactory implements ObjectFactory { private final static String PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
private final static String PROP_DEFAULTREADONLY = "defaultReadOnly";
private final static String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
private final static String PROP_DEFAULTCATALOG = "defaultCatalog";
private final static String PROP_DRIVERCLASSNAME = "driverClassName";
private final static String PROP_MAXACTIVE = "maxActive";
private final static String PROP_MAXIDLE = "maxIdle";
private final static String PROP_MINIDLE = "minIdle";
private final static String PROP_INITIALSIZE = "initialSize";
private final static String PROP_MAXWAIT = "maxWait";
private final static String PROP_TESTONBORROW = "testOnBorrow";
private final static String PROP_TESTONRETURN = "testOnReturn";
private final static String PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
private final static String PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
private final static String PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
private final static String PROP_TESTWHILEIDLE = "testWhileIdle";
private final static String PROP_PASSWORD = "password";
private final static String PROP_URL = "url";
private final static String PROP_USERNAME = "username";
private final static String PROP_VALIDATIONQUERY = "validationQuery";
private final static String PROP_VALIDATIONQUERY_TIMEOUT = "validationQueryTimeout";
/**
* The property name for initConnectionSqls.
* The associated value String must be of the form [query;]*
* @since 1.3
*/
private final static String PROP_INITCONNECTIONSQLS = "initConnectionSqls";
private final static String PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED = "accessToUnderlyingConnectionAllowed";
private final static String PROP_REMOVEABANDONED = "removeAbandoned";
private final static String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
private final static String PROP_LOGABANDONED = "logAbandoned";
private final static String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
private final static String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
private final static String PROP_CONNECTIONPROPERTIES = "connectionProperties"; private final static String[] ALL_PROPERTIES = {
PROP_DEFAULTAUTOCOMMIT,
PROP_DEFAULTREADONLY,
PROP_DEFAULTTRANSACTIONISOLATION,
PROP_DEFAULTCATALOG,
PROP_DRIVERCLASSNAME,
PROP_MAXACTIVE,
PROP_MAXIDLE,
PROP_MINIDLE,
PROP_INITIALSIZE,
PROP_MAXWAIT,
PROP_TESTONBORROW,
PROP_TESTONRETURN,
PROP_TIMEBETWEENEVICTIONRUNSMILLIS,
PROP_NUMTESTSPEREVICTIONRUN,
PROP_MINEVICTABLEIDLETIMEMILLIS,
PROP_TESTWHILEIDLE,
PROP_PASSWORD,
PROP_URL,
PROP_USERNAME,
PROP_VALIDATIONQUERY,
PROP_VALIDATIONQUERY_TIMEOUT,
PROP_INITCONNECTIONSQLS,
PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED,
PROP_REMOVEABANDONED,
PROP_REMOVEABANDONEDTIMEOUT,
PROP_LOGABANDONED,
PROP_POOLPREPAREDSTATEMENTS,
PROP_MAXOPENPREPAREDSTATEMENTS,
PROP_CONNECTIONPROPERTIES
}; // -------------------------------------------------- ObjectFactory Methods /**
* <p>Create and return a new <code>BasicDataSource</code> instance. If no
* instance can be created, return <code>null</code> instead.</p>
*
* @param obj The possibly null object containing location or
* reference information that can be used in creating an object
* @param name The name of this object relative to <code>nameCtx</code>
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or <code>null</code> if <code>name</code>
* is relative to the default initial context
* @param environment The possibly null environment that is used in
* creating this object
*
* @exception Exception if an exception occurs creating the instance
*/
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable environment)
throws Exception { // We only know how to deal with <code>javax.naming.Reference</code>s
// that specify a class name of "javax.sql.DataSource"
if ((obj == null) || !(obj instanceof Reference)) {
return null;
}
Reference ref = (Reference) obj;
if (!"javax.sql.DataSource".equals(ref.getClassName())) {
return null;
} Properties properties = new Properties();
for (int i = 0 ; i < ALL_PROPERTIES.length ; i++) {
String propertyName = ALL_PROPERTIES[i];
RefAddr ra = ref.get(propertyName);
if (ra != null) {
String propertyValue = ra.getContent().toString();
properties.setProperty(propertyName, propertyValue);
}
} return createDataSource(properties);
} /**
* Creates and configures a {@link BasicDataSource} instance based on the
* given properties.
*
* @param properties the datasource configuration properties
* @throws Exception if an error occurs creating the data source
*/
public static DataSource createDataSource(Properties properties) throws Exception {
BasicDataSource dataSource = new BasicDataSource();
String value = null; value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
if (value != null) {
dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_DEFAULTREADONLY);
if (value != null) {
dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
if (value != null) {
int level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
if ("NONE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_NONE;
}
else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_COMMITTED;
}
else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_UNCOMMITTED;
}
else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_REPEATABLE_READ;
}
else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_SERIALIZABLE;
}
else {
try {
level = Integer.parseInt(value);
} catch (NumberFormatException e) {
System.err.println("Could not parse defaultTransactionIsolation: " + value);
System.err.println("WARNING: defaultTransactionIsolation not set");
System.err.println("using default value of database driver");
level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
}
}
dataSource.setDefaultTransactionIsolation(level);
} value = properties.getProperty(PROP_DEFAULTCATALOG);
if (value != null) {
dataSource.setDefaultCatalog(value);
} value = properties.getProperty(PROP_DRIVERCLASSNAME);
if (value != null) {
dataSource.setDriverClassName(value);
} value = properties.getProperty(PROP_MAXACTIVE);
if (value != null) {
dataSource.setMaxActive(Integer.parseInt(value));
} value = properties.getProperty(PROP_MAXIDLE);
if (value != null) {
dataSource.setMaxIdle(Integer.parseInt(value));
} value = properties.getProperty(PROP_MINIDLE);
if (value != null) {
dataSource.setMinIdle(Integer.parseInt(value));
} value = properties.getProperty(PROP_INITIALSIZE);
if (value != null) {
dataSource.setInitialSize(Integer.parseInt(value));
} value = properties.getProperty(PROP_MAXWAIT);
if (value != null) {
dataSource.setMaxWait(Long.parseLong(value));
} value = properties.getProperty(PROP_TESTONBORROW);
if (value != null) {
dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_TESTONRETURN);
if (value != null) {
dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (value != null) {
dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
} value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
if (value != null) {
dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
} value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
if (value != null) {
dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
} value = properties.getProperty(PROP_TESTWHILEIDLE);
if (value != null) {
dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_PASSWORD);
if (value != null) {
dataSource.setPassword(value);
} value = properties.getProperty(PROP_URL);
if (value != null) {
dataSource.setUrl(value);
} value = properties.getProperty(PROP_USERNAME);
if (value != null) {
dataSource.setUsername(value);
} value = properties.getProperty(PROP_VALIDATIONQUERY);
if (value != null) {
dataSource.setValidationQuery(value);
} value = properties.getProperty(PROP_VALIDATIONQUERY_TIMEOUT);
if (value != null) {
dataSource.setValidationQueryTimeout(Integer.parseInt(value));
} value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
if (value != null) {
dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_REMOVEABANDONED);
if (value != null) {
dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
if (value != null) {
dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
} value = properties.getProperty(PROP_LOGABANDONED);
if (value != null) {
dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
} value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
} value = properties.getProperty(PROP_INITCONNECTIONSQLS);
if (value != null) {
StringTokenizer tokenizer = new StringTokenizer(value, ";");
dataSource.setConnectionInitSqls(Collections.list(tokenizer));
} value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
if (value != null) {
Properties p = getProperties(value);
Enumeration e = p.propertyNames();
while (e.hasMoreElements()) {
String propertyName = (String) e.nextElement();
dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
}
} // DBCP-215
// Trick to make sure that initialSize connections are created
if (dataSource.getInitialSize() > 0) {
dataSource.getLogWriter();
} // Return the configured DataSource instance
return dataSource;
} /**
* <p>Parse properties from the string. Format of the string must be [propertyName=property;]*<p>
* @param propText
* @return Properties
* @throws Exception
*/
static private Properties getProperties(String propText) throws Exception {
Properties p = new Properties();
if (propText != null) {
p.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes()));
}
return p;
}
}

day18 16.dbcp连接池使用介绍的更多相关文章

  1. DBCP连接池介绍

    DBCP连接池介绍 ----------------------------- 目前 DBCP 有两个版本分别是 1.3 和 1.4. DBCP 1.3 版本需要运行于 JDK 1.4-1.5 ,支持 ...

  2. 使用c3p0与DBCP连接池,造成的MySql 8小时问题解决方案

    转自:http://blog.csdn.net/wangfayinn/article/details/24623575 c3p0数据库连接池mysql8小时 目录(?)[-] 基本问题解决 项目环境 ...

  3. DBCP连接池简介

    DBCP连接池简介 1.数据库连接基础 数据库连接池基础主要包括以下三个方面的内容:数据库连接池的基本概念.数据库连接池的工作原理.Java开源的连接池.下面将从这三个方面一一介绍: (1)数据库连接 ...

  4. DBCP连接池原理分析及配置用法

    DBCP连接池介绍 ----------------------------- 目前 DBCP 有两个版本分别是 1.3 和 1.4. DBCP 1.3 版本需要运行于 JDK 1.4-1.5 ,支持 ...

  5. JNDI和在tomcat中配置DBCP连接池 元数据的使用 DBUtils框架的使用 多表操作

    1 JNDI和在tomcat中配置DBCP连接池 JNDI(Java Naming and Directory Interface),Java命名和目录接口,它对应于J2SE中的javax.namin ...

  6. JDBC连接池(三)DBCP连接池

    JDBC连接池(三)DBCP连接池 在前面的随笔中提到 了  1.JDBC自定义连接池  2. C3P0连接池 今天将介绍DBCP连接池 第一步要导入jar包   (注意:mysql和mysql 驱动 ...

  7. DBUtils工具类和DBCP连接池

    今日内容介绍 1.DBUtils2.处理结果集的八种方式3.连接池4.连接池的用法1 PrepareStatement接口预编译SQL语句 1.1 预处理对象 * 使用PreparedStatemen ...

  8. 使用c3p0与DBCP连接池,造成的MySql 8小时问题解决方式

    本文提供了对c3p0与DBCP连接池连接MySql数据库时. 8小时内无请求自己主动断开连接的解决方式.首先介绍一下我在项目(c3p0连接池)中遇到的问题,后面还提供了使用DBCP连接池的解决方式. ...

  9. DBCP连接池原理分析(转载)

    DBCP连接池介绍 ----------------------------- 目前 DBCP 有两个版本分别是 1.3 和 1.4. DBCP 1.3 版本需要运行于 JDK 1.4-1.5 ,支持 ...

随机推荐

  1. ES6数组对象新增方法

    1. Array.from() Array.from方法用于将两类对象转为真正的数组:类数组的对象( array-like object )和可遍历( iterable )的对象(包括 ES6 新增的 ...

  2. JeecgBoot 2.1.1 代码生成器AI版本发布,基于SpringBoot+AntDesign的JAVA快速开发平台

    此版本重点升级了 Online 代码生成器,支持更多的控件生成,所见即所得,极大的提高开发效率:同时做了数据库兼容专项工作,让 Online 开发兼容更多数据库:Mysql.SqlServer.Ora ...

  3. diskpart

    比如格式化成fat32 format fs=fat32 quick 比鼠标方便 如何使用: 打开cmd输入diskpart进入命令 首先 list disk 然后 然后 clean 然后 create ...

  4. python的命名规范

    包应该是简短的.小写的名字.如果下划线可以改善可读性可以加入.如mypackage. 模块与包的规范同.如mymodule. 类总是使用首字母大写单词串.如MyClass.内部类可以使用额外的前导下划 ...

  5. java基础之Date类

    Date类: Date类概述 类 Date 表示特定的瞬间,精确到毫秒. 构造方法 public Date() public Date(long date) 成员方法 public long getT ...

  6. 使用HTTP代理

    HTTP代理服务器可以比作客户端与Web服务器网站之间的一个信息中转站,客户端发送的HTTP请求和Web服务器返回的HTTP响应通过代理服务器转发给对方, 爬虫程序在爬取某些网站的时候也需要使用代理, ...

  7. pandas一些基本操作(DataFram和Series)_1

    ##生成一个一维数组import numpy as np;nb7 = np.arange(0,100,2);print(nb7)print("======================== ...

  8. sql里面插入语句insert后面的values关键字可省略

    插入到表名(列值)后跟一个查询语句的话就代表值,简单的说就是后面select select出来的值就是要插入的值,即  insert into tb(字段名一,字段名二)select 字段名一,字段名 ...

  9. 全栈之路-微信小程序-SKU开发(代码)

    SKU开发是小程序中最难的一部分,思路在分析中已经记录过了,这里主要看一下代码的实现,感觉老师写的代码太棒了,很优雅!主要想记录一下写代码的思路,对面向对象编程的实践. 一.代码结构的分析 1.说明几 ...

  10. 【NOIP2013模拟联考7】OSU

    [NOIP2013模拟联考7]OSU 描述 Description osu 是一款群众喜闻乐见的休闲软件. 我们可以把osu的规则简化与改编成以下的样子: 一共有n次操作,每次操作只有成功与失败之分, ...