zoukankan      html  css  js  c++  java
  • [转]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的实现类来进行配置。

    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.

    [java] view plain
      1. package dbcp;  
      2.   
      3. import java.sql.Connection;  
      4. import java.sql.ResultSet;  
      5. import java.sql.SQLException;  
      6. import java.sql.Statement;  
      7. import java.util.HashMap;  
      8. import java.util.Map;  
      9. import javax.sql.DataSource;  
      10. import org.apache.commons.dbcp2.BasicDataSource;  
      11.   
      12. /** 
      13.  * @author  
      14.  * @date  
      15.  * 
      16.  *       dbcp 实用类,提供了dbcp连接,不允许继承; 
      17.  *  
      18.  *       该类需要有个地方来初始化 DS ,通过调用initDS 方法来完成, 可以在通过调用带参数的构造函数完成调用, 
      19.  *       可以在其它类中调用,也可以在本类中加一个static{}来完成; 
      20.  */  
      21. public final class DbcpBean {  
      22.     /** 数据源,static */  
      23.     private static DataSource DS;  
      24.   
      25.     /** 从数据源获得一个连接 */  
      26.     public Connection getConn() {  
      27.         Connection con = null;  
      28.         if (DS != null) {  
      29.             try {  
      30.                 con = DS.getConnection();  
      31.             } catch (Exception e) {  
      32.                 e.printStackTrace(System.err);  
      33.             }  
      34.   
      35.             try {  
      36.                 con.setAutoCommit(false);  
      37.             } catch (SQLException e) {  
      38.                 e.printStackTrace();  
      39.             }  
      40.             return con;  
      41.         }  
      42.         return con;  
      43.     }  
      44.   
      45.     /** 默认的构造函数 */  
      46.     public DbcpBean() {  
      47.     }  
      48.   
      49.     /** 构造函数,初始化了 DS ,指定 数据库 */  
      50.     public DbcpBean(String connectURI) {  
      51.         initDS(connectURI);  
      52.     }  
      53.   
      54.     /** 构造函数,初始化了 DS ,指定 所有参数 */  
      55.     public DbcpBean(String connectURI, String username, String pswd,  
      56.             String driverClass, int initialSize, int maxActive, int maxIdle,  
      57.             int maxWait, int minIdle) {  
      58.         initDS(connectURI, username, pswd, driverClass, initialSize, maxActive,  
      59.                 maxIdle, maxWait, minIdle);  
      60.     }  
      61.   
      62.     /** 
      63.      * 创建数据源,除了数据库外,都使用硬编码默认参数; 
      64.      *  
      65.      * @param connectURI 
      66.      *            数据库 
      67.      * @return 
      68.      */  
      69.     public static void initDS(String connectURI) {  
      70.         initDS(connectURI, "root", "password", "com.mysql.jdbc.Driver", 5, 100,  
      71.                 30, 10000, 1);  
      72.     }  
      73.   
      74.     /** 
      75.      * 指定所有参数连接数据源 
      76.      *  
      77.      * @param connectURI 
      78.      *            数据库 
      79.      * @param username 
      80.      *            用户名 
      81.      * @param pswd 
      82.      *            密码 
      83.      * @param driverClass 
      84.      *            数据库连接驱动名 
      85.      * @param initialSize 
      86.      *            初始连接池连接个数 
      87.      * @param maxtotal 
      88.      *            最大活动连接数 
      89.      * @param maxIdle 
      90.      *            最大连接数 
      91.      * @param maxWaitMillis 
      92.      *            获得连接的最大等待毫秒数 
      93.      * @param minIdle 
      94.      *            最小连接数 
      95.      * @return 
      96.      */  
      97.     public static void initDS(String connectURI, String username, String pswd,  
      98.             String driverClass, int initialSize, int maxtotal, int maxIdle,  
      99.             int maxWaitMillis , int minIdle) {  
      100.         BasicDataSource ds = new BasicDataSource();  
      101.         ds.setDriverClassName(driverClass);  
      102.         ds.setUsername(username);  
      103.         ds.setPassword(pswd);  
      104.         ds.setUrl(connectURI);  
      105.         ds.setInitialSize(initialSize); // 初始的连接数;  
      106.         ds.setMaxTotal(maxtotal);  
      107.         ds.setMaxIdle(maxIdle);  
      108.         ds.setMaxWaitMillis(maxWaitMillis);  
      109.         ds.setMinIdle(minIdle);  
      110.         DS = ds;  
      111.     }  
      112.   
      113.     /** 获得数据源连接状态 */  
      114.     public static Map<String, Integer> getDataSourceStats() throws SQLException {  
      115.         BasicDataSource bds = (BasicDataSource) DS;  
      116.         Map<String, Integer> map = new HashMap<String, Integer>(2);  
      117.         map.put("active_number", bds.getNumActive());  
      118.         map.put("idle_number", bds.getNumIdle());  
      119.         return map;  
      120.     }  
      121.   
      122.     /** 关闭数据源 */  
      123.     protected static void shutdownDataSource() throws SQLException {  
      124.         BasicDataSource bds = (BasicDataSource) DS;  
      125.         bds.close();  
      126.     }  
      127.   
      128.     public static void main(String[] args) {  
      129.         DbcpBean db = new DbcpBean("jdbc:mysql://localhost:3306/testit");  
      130.         Connection conn = null;  
      131.         Statement stmt = null;  
      132.         ResultSet rs = null;  
      133.         try {  
      134.             conn = db.getConn();  
      135.             stmt = conn.createStatement();  
      136.             rs = stmt.executeQuery("select * from test limit 1 ");  
      137.             System.out.println("Results:");  
      138.             int numcols = rs.getMetaData().getColumnCount();  
      139.             while (rs.next()) {  
      140.                 for (int i = 1; i <= numcols; i++) {  
      141.                     System.out.print(" " + rs.getString(i) + " ");  
      142.                 }  
      143.                 System.out.println("");  
      144.             }  
      145.             System.out.println(getDataSourceStats());  
      146.         } catch (SQLException e) {  
      147.             e.printStackTrace();  
      148.         } finally {  
      149.             try {  
      150.                 if (rs != null)  
      151.                     rs.close();  
      152.                 if (stmt != null)  
      153.                     stmt.close();  
      154.                 if (conn != null)  
      155.                     conn.close();  
      156.                 if (db != null)  
      157.                     shutdownDataSource();  
      158.             } catch (Exception e) {  
      159.                 e.printStackTrace();  
      160.             }  
      161.         }  
      162.     }  
  • 相关阅读:
    poj-1001 求高精度幂
    ECS训练营Day1—基于阿里云ECS、VuePress搭建静态网站
    阿里云免费领马克杯答案
    白盒测试之逻辑覆盖 简单易懂~
    如何合并多个PPT?
    failed to connect to gitee.com/github/gitlab port 443: timed out之类的错误
    解决 These dependencies were not found: * core-js/modules/es6.array.fill in xxx 之类的问题
    vue内嵌iframe跨域通信
    Luffy之课程详情页
    Flask之SQLAlchemy,flask_session以及蓝图
  • 原文地址:https://www.cnblogs.com/dirgo/p/5222514.html
Copyright © 2011-2022 走看看