原文地址:http://blog.csdn.net/jiutianhe/article/details/39670817

dbcp 是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要3个包:common-dbcp.jar,common-pool.jar,common-collections.jar。

commons-pool的实现类来进行配置。

commons-pool1.6和commons-pool2.2分属commons-pool中两个不同的大版本,按照commons-pool官网上的介绍,Apache Commons Pool 2.2 (Java 6.0+),Apache Commons Pool 1.6 (Java 5.0+),即不同版本要求的JDK最低版本不同。
而commons-dbcp现在分成了3个大版本,不同的版本要求的JDK不同:
DBCP now comes in three different versions to support different versions of JDBC. Here is how it works:
Java
7 only (JDBC 4.1)
Java
6 only (JDBC 4)
Java
1.4-5 only (JDBC 3)

commons-dbcp2参数配置

由于commons-dbcp所用的连接池出现版本升级,因此commons-dbcp2中的数据库池连接配置也发生了变化,具体的参数配置说明如下:

Parameter Description

username

password url driverClassName connectionProperties Format of the string must be [propertyName=property;]* 

Parameter Default Description

defaultAutoCommit
defaultReadOnly
defaultTransactionIsolation

The default auto-commit state of connections created by this pool. If not set then the setAutoCommit method will not be called.
The default read-only state of connections created by this pool. If not
set then the setReadOnly method will not be called. (Some drivers don't
support read only mode, ex: Informix)
The default TransactionIsolation state of connections created by this pool. One of the following: (see

  • READ_COMMITTED
  • REPEATABLE_READ
  • defaultCatalog
  cacheState If true, the pooled connection will cache the current readOnly and
autoCommit settings when first read or written and on all subsequent
writes. This removes the need for additional database queries for any
further calls to the getter. If the underlying connection
is accessed directly and the readOnly and/or autoCommit settings
changed the cached values will not reflect the current state. In this
case, caching should be disabled by setting this attribute to false.

    1. package dbcp;
    2. import java.sql.Connection;
    3. import java.sql.ResultSet;
    4. import java.sql.SQLException;
    5. import java.sql.Statement;
    6. import java.util.HashMap;
    7. import java.util.Map;
    8. import javax.sql.DataSource;
    9. import org.apache.commons.dbcp2.BasicDataSource;
    10. /**
    11. * @author
    12. * @date
    13. *
    14. *       dbcp 实用类,提供了dbcp连接,不允许继承;
    15. *
    16. *       该类需要有个地方来初始化 DS ,通过调用initDS 方法来完成, 可以在通过调用带参数的构造函数完成调用,
    17. *       可以在其它类中调用,也可以在本类中加一个static{}来完成;
    18. */
    19. public final class DbcpBean {
    20. /** 数据源,static */
    21. private static DataSource DS;
    22. /** 从数据源获得一个连接 */
    23. public Connection getConn() {
    24. Connection con = null;
    25. if (DS != null) {
    26. try {
    27. con = DS.getConnection();
    28. } catch (Exception e) {
    29. e.printStackTrace(System.err);
    30. }
    31. try {
    32. con.setAutoCommit(false);
    33. } catch (SQLException e) {
    34. e.printStackTrace();
    35. }
    36. return con;
    37. }
    38. return con;
    39. }
    40. /** 默认的构造函数 */
    41. public DbcpBean() {
    42. }
    43. /** 构造函数,初始化了 DS ,指定 数据库 */
    44. public DbcpBean(String connectURI) {
    45. initDS(connectURI);
    46. }
    47. /** 构造函数,初始化了 DS ,指定 所有参数 */
    48. public DbcpBean(String connectURI, String username, String pswd,
    49. String driverClass, int initialSize, int maxActive, int maxIdle,
    50. int maxWait, int minIdle) {
    51. initDS(connectURI, username, pswd, driverClass, initialSize, maxActive,
    52. maxIdle, maxWait, minIdle);
    53. }
    54. /**
    55. * 创建数据源,除了数据库外,都使用硬编码默认参数;
    56. *
    57. * @param connectURI
    58. *            数据库
    59. * @return
    60. */
    61. public static void initDS(String connectURI) {
    62. initDS(connectURI, "root", "password", "com.mysql.jdbc.Driver", 5, 100,
    63. 30, 10000, 1);
    64. }
    65. /**
    66. * 指定所有参数连接数据源
    67. *
    68. * @param connectURI
    69. *            数据库
    70. * @param username
    71. *            用户名
    72. * @param pswd
    73. *            密码
    74. * @param driverClass
    75. *            数据库连接驱动名
    76. * @param initialSize
    77. *            初始连接池连接个数
    78. * @param maxtotal
    79. *            最大活动连接数
    80. * @param maxIdle
    81. *            最大连接数
    82. * @param maxWaitMillis
    83. *            获得连接的最大等待毫秒数
    84. * @param minIdle
    85. *            最小连接数
    86. * @return
    87. */
    88. public static void initDS(String connectURI, String username, String pswd,
    89. String driverClass, int initialSize, int maxtotal, int maxIdle,
    90. int maxWaitMillis , int minIdle) {
    91. BasicDataSource ds = new BasicDataSource();
    92. ds.setDriverClassName(driverClass);
    93. ds.setUsername(username);
    94. ds.setPassword(pswd);
    95. ds.setUrl(connectURI);
    96. ds.setInitialSize(initialSize); // 初始的连接数;
    97. ds.setMaxTotal(maxtotal);
    98. ds.setMaxIdle(maxIdle);
    99. ds.setMaxWaitMillis(maxWaitMillis);
    100. ds.setMinIdle(minIdle);
    101. DS = ds;
    102. }
    103. /** 获得数据源连接状态 */
    104. public static Map<String, Integer> getDataSourceStats() throws SQLException {
    105. BasicDataSource bds = (BasicDataSource) DS;
    106. Map<String, Integer> map = new HashMap<String, Integer>(2);
    107. map.put("active_number", bds.getNumActive());
    108. map.put("idle_number", bds.getNumIdle());
    109. return map;
    110. }
    111. /** 关闭数据源 */
    112. protected static void shutdownDataSource() throws SQLException {
    113. BasicDataSource bds = (BasicDataSource) DS;
    114. bds.close();
    115. }
    116. public static void main(String[] args) {
    117. DbcpBean db = new DbcpBean("jdbc:mysql://localhost:3306/testit");
    118. Connection conn = null;
    119. Statement stmt = null;
    120. ResultSet rs = null;
    121. try {
    122. conn = db.getConn();
    123. stmt = conn.createStatement();
    124. rs = stmt.executeQuery("select * from test limit 1 ");
    125. System.out.println("Results:");
    126. int numcols = rs.getMetaData().getColumnCount();
    127. while (rs.next()) {
    128. for (int i = 1; i <= numcols; i++) {
    129. System.out.print("\t" + rs.getString(i) + "\t");
    130. }
    131. System.out.println("");
    132. }
    133. System.out.println(getDataSourceStats());
    134. } catch (SQLException e) {
    135. e.printStackTrace();
    136. } finally {
    137. try {
    138. if (rs != null)
    139. rs.close();
    140. if (stmt != null)
    141. stmt.close();
    142. if (conn != null)
    143. conn.close();
    144. if (db != null)
    145. shutdownDataSource();
    146. } catch (Exception e) {
    147. e.printStackTrace();
    148. }
    149. }
    150. }
    151. }

[转]Java使用commons-dbcp2.0的更多相关文章

  1. Dbcp2抛出org.apache.commons.dbcp2.LifetimeExceededException

    三月 24, 2016 5:16:33 下午 org.apache.commons.dbcp2.BasicDataSource onSwallowException 警告: An internal o ...

  2. Java I/O 从0到1 - 第Ⅰ滴血 File

    前言 File 类的介绍主要会依据<Java 编程思想>以及官网API .相信大家在日常工作中,肯定会遇到文件流的读取等操作,但是在搜索过程中,并没有找到一个介绍的很简洁明了的文章.因此, ...

  3. Failed to unregister the JMX name: org.apache.commons.dbcp2:name=xxx,type=BasicDataSource

    把datesource的bean的class由 org.apache.commons.dbcp2.BasicDataSource 改成 org.apache.tomcat.dbcp.dbcp.Basi ...

  4. 《Java I/O 从0到1》 - 第Ⅰ滴血 File

    前言 File 类的介绍主要会依据<Java 编程思想>以及官网API .相信大家在日常工作中,肯定会遇到文件流的读取等操作,但是在搜索过程中,并没有找到一个介绍的很简洁明了的文章.因此, ...

  5. 20145208 《Java程序设计》第0周学习总结

    20145208 <Java程序设计>第0周学习总结 阅读心得 读了老师推荐的几个文章,虽然第四个文章"为什么一定要自学"报告资源不存在而无法阅读,其他的三篇文章都言之 ...

  6. 《Java I/O 从0到1》 - 第Ⅱ滴血 “流”

    前言 <Java I/O 从0到1>系列上一章节,介绍了File 类,这一章节介绍的是IO的核心 输入输出.I/O类库常使用流这个抽象概念.代表任何有能力产出数据的数据源对象或者是有能力接 ...

  7. Windows Intellij环境下Gradle的 “Could not determine Java version from ‘9.0.1’”的解决方式

    当我导入Gradle项目初试Java spring的时候,遇到下面报错: Gradle complete project refresh failed Error:Could not determin ...

  8. hadoop 遇到java.net.ConnectException: to 0.0.0.0:10020 failed on connection

      hadoop 遇到java.net.ConnectException: to 0.0.0.0:10020 failed on connection   这个问题一般是在hadoop2.x版本里会出 ...

  9. 20145328 《Java程序设计》第0周学习总结

    20145328 <Java程序设计>第0周学习总结 阅读心得 从总体上来说,这几篇文章都是围绕着软件工程专业的一些现象来进行描述的,但深入了解之后就可以发现,无论是软件工程专业还是我们现 ...

  10. Java升级替换java version "1.5.0"

    首先进行java安装 http://www.cnblogs.com/someone9/p/8670585.html 2. 然后查看版本信息,仍然是1.5.0 [root@OKC java]# java ...

随机推荐

  1. NOIP2009 提高组T3 机器翻译 解题报告-S.B.S

    题目背景 小晨的电脑上安装了一个机器翻译软件,他经常用这个软件来翻译英语文章. 题目描述 这个翻译软件的原理很简单,它只是从头到尾,依次将每个英文单词用对应的中文含义来替换.对于每个英文单词,软件会先 ...

  2. namesilo域名注册教程

    一.注册账号 打开http://www.namesilo.com ,我们先去注册一个Namesilo帐号,然后再在Namesilo注册域名!如图: 接下来,就是填写一些简单资料,如图: 然后Names ...

  3. unity3d 的Quaternion.identity和transform.rotation区别是什么

    Quaternion.identity就是指Quaternion(0,0,0,0),就是每旋转前的初始角度,是一个确切的值,而transform.rotation是指本物体的角度,值是不确定的,比如可 ...

  4. 在JAVA中,关于反射机制的讨论

    一.什么是反射机制         简单的来说,反射机制指的是程序在运行时能够获取自身的信息.在java中,只要给定类的名字,     那么就可以通过反射机制来获得类的所有信息. 二.哪里用到反射机制 ...

  5. flexslider.js和waypoints.js一起用时的巨坑

    Flexslider has a callback API where you can execute functions after various actions:https://github.c ...

  6. java 22 - 11 多线程之模拟电影院售票口售票

    使用多线程实现的第二种方式: 首先创建自定义类 public class SellTicket implements Runnable { // 定义100张票 private int ticket ...

  7. JS常用方法函数整理

    1.document.write("");为输出语句 2.JS中的注释为// 3.传统的HTML文档顺序是:document->html->(head,body) 4. ...

  8. 配置Tomcat使用Redis作为session管理

    1. 在 tomcat/lib 中增加以下jar包 commons-pool2-.jar jedis-.jar tomcat-redis-session-manager-.jar 2. 修改tomca ...

  9. 在Java代码中使用pdfBox将PDF转换为图片

    生成图片 // 生成图片 PDDocument pd = PDDocument.load(new File(filePath)); PDFRenderer pdfRenderer = new PDFR ...

  10. NodeJS 开篇 牛刀小试

    一.Node&NPM的安装与配置 下载:https://nodejs.org/en/ V4.2.x LTS(9.75MB)——长期支持版,成熟可靠 V5.x.x Stable(9.71MB)— ...