码迷,mamicode.com
首页 > 数据库 > 详细

C3P0与DBCP的使用

时间:2016-05-12 09:11:17      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

(一)C3P0

C3P0是Hibernate推荐使用的连接池,可自动清理connection、Statement、ResultSet,需要依赖C3P0的jar包。

配置文件

DriverClass=com.mysql.jdbc.Driver
JdbcUrl=jdbc:mysql://127.0.0.1:3306/mydb
User=root
Password =w5566
MaxPoolSize=40
MinPoolSize=2
InitialPoolSize=10
MaxStatements=180

java实现

public Connection c3p0Conn() {
        // 加载配置文件
        Properties props = new Properties();
        String filename = "/com/awinson/cfg/c3p0.properties";
        InputStream is = this.getClass().getResourceAsStream(filename);

        try {
            props.load(is);            
            // 创建连接池实例
            ComboPooledDataSource dSource = new ComboPooledDataSource();
            // 配置数据源
            dSource.setDriverClass(props.getProperty("DriverClass"));
            dSource.setJdbcUrl(props.getProperty("JdbcUrl"));
            dSource.setUser(props.getProperty("User"));
            dSource.setPassword(props.getProperty("Password"));
            dSource.setMaxPoolSize(Integer.parseInt(props.getProperty("MaxPoolSize")));
            dSource.setMinPoolSize(Integer.parseInt(props.getProperty("MinPoolSize")));
            dSource.setInitialPoolSize(Integer.parseInt(props.getProperty("InitialPoolSize")));
            dSource.setMaxStatements(Integer.parseInt(props.getProperty("MaxStatements")));
            //获取数据库连接
            Connection conn = dSource.getConnection();
            //关闭事务自动提交
            conn.setAutoCommit(false);
            return conn;
        } catch (PropertyVetoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

 

 

(二)DBCP

DBCP是Apache基金会的开源连接池,需要依赖commons-dbcp.jar和commons-pool.jar这两个jar包。

    //创建数据源对象
    BasicDataSource ds = new BasicDataSource();
    //配置数据源
    ds.setDriver(driver);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setInitialSize(initialSize);
    ds.setMaxIdle(maxIdle);
    ds.setMinIdle(minIdle);
    //获取数据库连接
    Connection conn = ds.getConnection();
    
    
    //释放数据库连接
    conn.close();

 

 

(三)补充

(1)数据源只需创建一个,它是数据库连接的工厂。

(2)建议把数据源设置成static对象,在应用开始时初始化数据源对象,程序中需要获取数据链接的地方直接访问ds对象。

 

C3P0与DBCP的使用

标签:

原文地址:http://www.cnblogs.com/iwinson/p/5484338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!