dbcp的简单使用_数据库连接池

来源:互联网 发布:淘宝优惠券分享赚佣金 编辑:程序博客网 时间:2024/05/16 19:39
  1. 一.package dbutil;
  2. import javax.sql.*;
  3. import java.sql.*;
  4. import org.apache.commons.dbcp.BasicDataSource;
  5. /**
  6.  * 数据库连接类,使用了DBCP 数据库连接池
  7.  * 
  8.  */
  9. public class DBConnection {
  10.     private static DataSource ds = null;
  11.     private static boolean poolOK = false;
  12.     final static String DBDRIVER = "com.mysql.jdbc.Driver";
  13.     final static String DBURL = "jdbc:mysql://localhost:3306/test";
  14.     final static String DBUSER = "root";
  15.     final static String DBPWD = "root";
  16.     /**
  17.      * 取得数据库连接
  18.      * 
  19.      * @return 一个数据池中的连接
  20.      */
  21.     public static Connection getConnection() {
  22.         // 如果连接池未安装 或 连接池坏死, 安装连接池
  23.         if (null == ds || false == poolOK) {
  24.             ds = setupDataSource();
  25.         }
  26.         Connection con = null;
  27.         
  28.         try {
  29.             con = ds.getConnection();
  30.             poolOK = true;
  31.             //检测连接是否有效,如果无效,会抛出异常
  32.             //con.prepareStatement("select * from tab");
  33.         } catch (SQLException e) {
  34.             poolOK = false;
  35.             shutdownDataSource(ds);
  36.             System.out.println("数据库意外关闭" + e);
  37.         }
  38.         return con;
  39.     }
  40.     /**
  41.      * 安装连接池
  42.      * 
  43.      * @return 连接池对象
  44.      * 
  45.      */
  46.     private static DataSource setupDataSource() {
  47.         BasicDataSource bds = new BasicDataSource();
  48.         bds.setDriverClassName(DBDRIVER);
  49.         bds.setUrl(DBURL);
  50.         bds.setUsername(DBUSER);
  51.         bds.setPassword(DBPWD);
  52.         bds.setInitialSize(10);
  53.         bds.setMaxActive(30);
  54.         return bds;
  55.     }
  56.     /**
  57.      * 关闭连接池
  58.      */
  59.     private static void shutdownDataSource(DataSource ds) {
  60.         BasicDataSource bds = (BasicDataSource) ds;
  61.         try {
  62.             bds.close();
  63.         } catch (SQLException e) {
  64.             e.printStackTrace();
  65.         }
  66.     }
  67.     /**
  68.      * 打印 数据库连接池状态
  69.      * @param ds
  70.      * @throws SQLException
  71.      */
  72.      public static void printDataSourceStats()  {
  73.             BasicDataSource bds = (BasicDataSource) ds;
  74.             System.out.println("NumActive: " + bds.getNumActive());
  75.             System.out.println("NumIdle: " + bds.getNumIdle());
  76.         }
  77.     private DBConnection() {
  78.     }
  79.     public static void main(String[] args) {
  80.         getConnection();
  81.         getConnection();
  82.         printDataSourceStats();
  83.     }
  84. }
  85. 二.
  86. package dbcp;
  87. import java.sql.*;
  88. import org.apache.commons.pool.ObjectPool;
  89. import org.apache.commons.pool.impl.GenericObjectPool;
  90. import org.apache.commons.dbcp.ConnectionFactory;
  91. import org.apache.commons.dbcp.PoolingDriver;
  92. import org.apache.commons.dbcp.PoolableConnectionFactory;
  93. import org.apache.commons.dbcp.DriverManagerConnectionFactory;
  94. /*the class connect to oracle with thin methord*/
  95. public class DBPoolUtil {
  96.     // the orcale jdbc dirver
  97.     //static String driver = "oracle.jdbc.driver.OracleDriver";
  98.     static String driver = "com.mysql.jdbc.Driver";
  99.     // the connection is used to connect to database or dbcp
  100.     private Connection conn = null;
  101.     // the statement is used to execute SQL statement in database
  102.     private Statement stmt = null;
  103.     // the exact database URI locate in database
  104.     //private static String sqlJdbc = "jdbc:oracle:thin:@192.168.0.77:1521:OEMTEP";
  105.     private static String sqlJdbc = "jdbc:mysql://localhost:3306/test";
  106.     // use name
  107.     private static String sqlUser = "root";
  108.     // password
  109.     private static String sqlPwd = "root";
  110.     // the class file of oracle jdbc make it get .class file dynamiclly
  111.     private static Class driverClass = null;
  112.     // the pointer which presents DBPC
  113.     private static ObjectPool connectionPool = null;
  114.     // the construct methord is automaticlly connect to the database for user
  115.     public DBPoolUtil() {
  116.         initDataSource();
  117.     }
  118.     // connect to oracle and print some information about it
  119.     // and synchronized make the pool used a user one time
  120.     private synchronized static void initDataSource() {
  121.         if (driverClass == null) {
  122.             try {
  123.                 // load the  jdbc
  124.                 driverClass = Class.forName(driver);
  125.             } catch (ClassNotFoundException e) {
  126.                 e.printStackTrace();
  127.             }
  128.         }
  129.         if (connectionPool == null) {
  130.             try {
  131.                 setupDriver(sqlJdbc);
  132.             } catch (Exception e) {
  133.                 e.printStackTrace();
  134.             }
  135.         }
  136.         // Display some pool statistics
  137.         try {
  138.             printDriverStats();
  139.         } catch (Exception e) {
  140.             e.printStackTrace();
  141.         }
  142.     }
  143.     private static void setupDriver(String connectURI) throws Exception {
  144.         // get pool connection of DBPC
  145.         connectionPool = new GenericObjectPool(null);
  146.         ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
  147.                 connectURI, sqlUser, sqlPwd);
  148.         PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
  149.                 connectionFactory, connectionPool, nullnullfalsetrue);
  150.         Class.forName("org.apache.commons.dbcp.PoolingDriver");
  151.         PoolingDriver driver = (PoolingDriver) DriverManager
  152.                 .getDriver("jdbc:apache:commons:dbcp:");
  153.         //   
  154.         driver.registerPool("auxdbpoll", connectionPool);
  155.     }
  156.     private static void printDriverStats() throws Exception {
  157.         PoolingDriver driver = (PoolingDriver) DriverManager
  158.                 .getDriver("jdbc:apache:commons:dbcp:");
  159.         ObjectPool connectionPool = driver.getConnectionPool("auxdbpoll");
  160.         System.out.println("active connection: "
  161.                 + connectionPool.getNumActive());
  162.         System.out.println("idle connection:  " + connectionPool.getNumIdle());
  163.     }
  164.     // the a connection from the pool
  165.     public Connection getConnection() {
  166.         try {
  167.             conn = DriverManager
  168.                     .getConnection("jdbc:apache:commons:dbcp:auxdbpoll");
  169.         } catch (SQLException e) {
  170.             e.printStackTrace();
  171.         }
  172.         return conn;
  173.     }
  174.     /** 
  175.      * 释放连接池 
  176.      */ 
  177.     public static void ShutdownPool() { 
  178.         try { 
  179.             PoolingDriver driver = (PoolingDriver) DriverManager 
  180.                     .getDriver("jdbc:apache:commons:dbcp:"); 
  181.             driver.closePool("auxdbpoll"); 
  182.         } catch (SQLException e) { 
  183.             e.printStackTrace();
  184.         } 
  185.     } 
  186. }