利用Oracle自带的连接缓冲类的一个例子.

发表于:2007-07-04来源:作者:点击数: 标签:
import java . sql .Connection; import oracle .jdbc.pool. Oracle ConnectionCacheImpl; /** * 连接池管理类 */ public class DBPool { /** 连接池 */ private static OracleConnectionCacheImpl pool = null; /** * 初始化连接池 */ public static void in
import java.sql.Connection;
import oracle.jdbc.pool.OracleConnectionCacheImpl;

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

    /** 连接池 */
    private static OracleConnectionCacheImpl 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());
    }

}

//连接池参考: http://www.dev-club.com/club/bbs/showEssence.asp?id=20500&page=2
//参考:Oracle9i文档资料

原文转自:http://www.ltesting.net