[转]Java使用commons-dbcp2.0
原文地址: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的实现类来进行配置。
7 only (JDBC 4.1)
6 only (JDBC 4)
1.4-5 only (JDBC 3)
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
|
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. |
- package dbcp;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.HashMap;
- import java.util.Map;
- import javax.sql.DataSource;
- import org.apache.commons.dbcp2.BasicDataSource;
- /**
- * @author
- * @date
- *
- * dbcp 实用类,提供了dbcp连接,不允许继承;
- *
- * 该类需要有个地方来初始化 DS ,通过调用initDS 方法来完成, 可以在通过调用带参数的构造函数完成调用,
- * 可以在其它类中调用,也可以在本类中加一个static{}来完成;
- */
- public final class DbcpBean {
- /** 数据源,static */
- private static DataSource DS;
- /** 从数据源获得一个连接 */
- public Connection getConn() {
- Connection con = null;
- if (DS != null) {
- try {
- con = DS.getConnection();
- } catch (Exception e) {
- e.printStackTrace(System.err);
- }
- try {
- con.setAutoCommit(false);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return con;
- }
- return con;
- }
- /** 默认的构造函数 */
- public DbcpBean() {
- }
- /** 构造函数,初始化了 DS ,指定 数据库 */
- public DbcpBean(String connectURI) {
- initDS(connectURI);
- }
- /** 构造函数,初始化了 DS ,指定 所有参数 */
- public DbcpBean(String connectURI, String username, String pswd,
- String driverClass, int initialSize, int maxActive, int maxIdle,
- int maxWait, int minIdle) {
- initDS(connectURI, username, pswd, driverClass, initialSize, maxActive,
- maxIdle, maxWait, minIdle);
- }
- /**
- * 创建数据源,除了数据库外,都使用硬编码默认参数;
- *
- * @param connectURI
- * 数据库
- * @return
- */
- public static void initDS(String connectURI) {
- initDS(connectURI, "root", "password", "com.mysql.jdbc.Driver", 5, 100,
- 30, 10000, 1);
- }
- /**
- * 指定所有参数连接数据源
- *
- * @param connectURI
- * 数据库
- * @param username
- * 用户名
- * @param pswd
- * 密码
- * @param driverClass
- * 数据库连接驱动名
- * @param initialSize
- * 初始连接池连接个数
- * @param maxtotal
- * 最大活动连接数
- * @param maxIdle
- * 最大连接数
- * @param maxWaitMillis
- * 获得连接的最大等待毫秒数
- * @param minIdle
- * 最小连接数
- * @return
- */
- public static void initDS(String connectURI, String username, String pswd,
- String driverClass, int initialSize, int maxtotal, int maxIdle,
- int maxWaitMillis , int minIdle) {
- BasicDataSource ds = new BasicDataSource();
- ds.setDriverClassName(driverClass);
- ds.setUsername(username);
- ds.setPassword(pswd);
- ds.setUrl(connectURI);
- ds.setInitialSize(initialSize); // 初始的连接数;
- ds.setMaxTotal(maxtotal);
- ds.setMaxIdle(maxIdle);
- ds.setMaxWaitMillis(maxWaitMillis);
- ds.setMinIdle(minIdle);
- DS = ds;
- }
- /** 获得数据源连接状态 */
- public static Map<String, Integer> getDataSourceStats() throws SQLException {
- BasicDataSource bds = (BasicDataSource) DS;
- Map<String, Integer> map = new HashMap<String, Integer>(2);
- map.put("active_number", bds.getNumActive());
- map.put("idle_number", bds.getNumIdle());
- return map;
- }
- /** 关闭数据源 */
- protected static void shutdownDataSource() throws SQLException {
- BasicDataSource bds = (BasicDataSource) DS;
- bds.close();
- }
- public static void main(String[] args) {
- DbcpBean db = new DbcpBean("jdbc:mysql://localhost:3306/testit");
- Connection conn = null;
- Statement stmt = null;
- ResultSet rs = null;
- try {
- conn = db.getConn();
- stmt = conn.createStatement();
- rs = stmt.executeQuery("select * from test limit 1 ");
- System.out.println("Results:");
- int numcols = rs.getMetaData().getColumnCount();
- while (rs.next()) {
- for (int i = 1; i <= numcols; i++) {
- System.out.print("\t" + rs.getString(i) + "\t");
- }
- System.out.println("");
- }
- System.out.println(getDataSourceStats());
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if (rs != null)
- rs.close();
- if (stmt != null)
- stmt.close();
- if (conn != null)
- conn.close();
- if (db != null)
- shutdownDataSource();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
[转]Java使用commons-dbcp2.0的更多相关文章
- Dbcp2抛出org.apache.commons.dbcp2.LifetimeExceededException
三月 24, 2016 5:16:33 下午 org.apache.commons.dbcp2.BasicDataSource onSwallowException 警告: An internal o ...
- Java I/O 从0到1 - 第Ⅰ滴血 File
前言 File 类的介绍主要会依据<Java 编程思想>以及官网API .相信大家在日常工作中,肯定会遇到文件流的读取等操作,但是在搜索过程中,并没有找到一个介绍的很简洁明了的文章.因此, ...
- 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 ...
- 《Java I/O 从0到1》 - 第Ⅰ滴血 File
前言 File 类的介绍主要会依据<Java 编程思想>以及官网API .相信大家在日常工作中,肯定会遇到文件流的读取等操作,但是在搜索过程中,并没有找到一个介绍的很简洁明了的文章.因此, ...
- 20145208 《Java程序设计》第0周学习总结
20145208 <Java程序设计>第0周学习总结 阅读心得 读了老师推荐的几个文章,虽然第四个文章"为什么一定要自学"报告资源不存在而无法阅读,其他的三篇文章都言之 ...
- 《Java I/O 从0到1》 - 第Ⅱ滴血 “流”
前言 <Java I/O 从0到1>系列上一章节,介绍了File 类,这一章节介绍的是IO的核心 输入输出.I/O类库常使用流这个抽象概念.代表任何有能力产出数据的数据源对象或者是有能力接 ...
- Windows Intellij环境下Gradle的 “Could not determine Java version from ‘9.0.1’”的解决方式
当我导入Gradle项目初试Java spring的时候,遇到下面报错: Gradle complete project refresh failed Error:Could not determin ...
- 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版本里会出 ...
- 20145328 《Java程序设计》第0周学习总结
20145328 <Java程序设计>第0周学习总结 阅读心得 从总体上来说,这几篇文章都是围绕着软件工程专业的一些现象来进行描述的,但深入了解之后就可以发现,无论是软件工程专业还是我们现 ...
- Java升级替换java version "1.5.0"
首先进行java安装 http://www.cnblogs.com/someone9/p/8670585.html 2. 然后查看版本信息,仍然是1.5.0 [root@OKC java]# java ...
随机推荐
- Stanford机器学习笔记-7. Machine Learning System Design
7 Machine Learning System Design Content 7 Machine Learning System Design 7.1 Prioritizing What to W ...
- mysql中char与varchar的区别分析
char 固定长度,所以在处理速度上要比varchar快速很多,但是对费存储空间,所以对存储不大,但在速度上有要求的可以使用char类型,反之可以用varchar类型来实例 建意: myisam 存储 ...
- java 22 - 22 多线程之 匿名内部类的方式实现多线程
首先回顾下之前的匿名内部类: 匿名内部类的格式: new 接口或者接口名(){ 重写方法 }; 本质:是该类或者接口的子类对象 匿名内部类方式使用多线程 1.new Thread(){代码-}.sta ...
- PPT文档页数显示的增加和更新
在PPT的右下角增加页数的显示能够帮助演讲者把握进度,所以会经常遇到需要把页数显示在右下角的情况,这次在制作ppt的时候也遇到了.因此在这里总结一下设置方法. 一.在右下角显示当前页数和总页数 1)获 ...
- ef操作类
基于Hi博客的类库 20160811 using Model; using System; using System.Collections.Generic; using System.Data.En ...
- 关于codeMirror插件使用的一个坑
codeMirror插件可以做语法高亮渲染,但它操作过程是这样的:先从 textarea中读取值放到codemirror动态生成的div中,根据textarea中的换行个数确定行数,根据正则表达来高亮 ...
- wechat开发
1.easywechat安装 2.weichat打通服务器 function getTest(Request $request){ $token = 'zhenhaokeji'; $data = $r ...
- KindEditor得不到textarea值的解决方法
转自:http://blog.phpha.com/archives/510.html 以前有朋友遇到过这个问题,就是KindEditor在火狐下或者其他浏览器下都无法得到textarea文本框的值,点 ...
- FineUI v4.0.2 (beta) 发布了!
FineUI v4.0.2 (beta) 已经于 2013-12-15 发布! ================================== 关于FineUI基于 ExtJS 的开源 ASP. ...
- ASP.NET MVC运行机制源码剖析
我们都知道ASP.NET首先是从Global.aspx中开始运行的, 在Application_Start()中添加路由映射后, 就由URLRouting组件创建IRouteHandler并执行, 在 ...