当前位置:Gxlcms > 数据库问题 > C3P0与DBCP的使用

C3P0与DBCP的使用

时间:2021-07-01 10:21:17 帮助过:4人阅读

配置文件

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的使用

标签:

人气教程排行