Chinaunix首页 | 论坛 | 博客
  • 博客访问: 616726
  • 博文数量: 825
  • 博客积分: 5000
  • 博客等级: 大校
  • 技术积分: 4980
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-27 14:19
文章分类

全部博文(825)

文章存档

2011年(1)

2008年(824)

我的朋友

分类:

2008-10-27 14:26:33

    import java.sql.Connection;
    import oracle.jdbc.pool.ConnectionCacheImpl;

/**
* 连接池管理类
*/
public class DBPool {

    /** 连接池 */
    private static ConnectionCacheImpl pool = null;

    /**
     * 初始化连接池
     */
    public static void init() {

        try{
            String user = "user";                   //用户名
            String password = "pwd";          //密码
            String host = "127.0.0.1";          //Server地址
            String port = "1521";                 //端口
            String sid = "oracle92";              //SID
            int max = 20;                             //最大连接数
            int min = 5;                                //最小连接数

            //拼连接字符串
            String url = "jdbc:oracle:thin:@" + host + ":" + port + ":" + sid;

            //实例化连接池并设置参数
            pool = new OracleConnectionCacheImpl();
            pool.setURL(url);
            pool.setPassword(password);
            pool.setUser(user);
            pool.setMaxLimit(max);
            pool.setMinLimit(min);

            /**
             * 设置连接数超限时增加方式.
             * DYNAMIC_SCHEME:是动态增加.用完如果超过上限则关掉.
             * 还有两个.1.直接返回Null .2.始终等待
             */
            pool.setCacheScheme(OracleConnectionCacheImpl.DYNAMIC_SCHEME);

            /**
             * 如果你已经有个连接池了.
             * 比如是OracleConnectionPoolDataSource ocpds;
             * 可以直接设置.前面的设置就不用了.或者直接写在构造器里.
             */
            //pool.setConnectionPoolDataSource(ocpds);

        }catch(Exception ex) {
        }

    }

    /**
     * 终了处理.
     * 比如在APP关掉前调用.
     */
    public static void destory() {
        if(pool != null) {
            try {
                pool.close();
                pool = null;
            }catch(Exception ex) {
            }
        }
    }

    /**
     * 取连接.
     * 和其他的连接一样正常用.
     * @return 连接
     */
    public static Connection getConnection() {
        try{
            Connection conn = pool.getConnection();
            return conn;
        }catch(Exception e){
            return null;
        }
    }

    /**
     * 调试
     */
    public static void turnning() {
        System.out.println("Active Conns:"+pool.getActiveSize());
        System.out.println("Cached Conns:"+pool.getCacheSize());
    }

}

【责编:Youping】

--------------------next---------------------

阅读(448) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~