Java:C3P0连接池

C3P0连接池的两种使用方式
方式一:相关参数,在程序中指定user, url, password等

//方式1:相关参数,在程序中指定user, url, password等
@Test
public void testC3P0_01() throws Exception {

    //1.创建一个数据源对象
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    //2.通过配置文件mysql.properties获取相关的连接信息
    Properties properties = new Properties();
    properties.load(new FileInputStream("src/mysql.properties"));
    //读取相关的值
    String driver = properties.getProperty("driver");
    String url = properties.getProperty("url");
    String user = properties.getProperty("user");
    String password = properties.getProperty("password");

    //给数据源 comboPooledDataSource 设置相关的参数
    //注意:连接管理是由 comboPooledDataSource 来管理
    comboPooledDataSource.setDriverClass(driver);
    comboPooledDataSource.setJdbcUrl(url);
    comboPooledDataSource.setUser(user);
    comboPooledDataSource.setPassword(password);

    //设置初始化连接数
    comboPooledDataSource.setInitialPoolSize(10);
    //最大连接数
    comboPooledDataSource.setMaxPoolSize(50);
    //测试连接池的效率,测试对mysql 5000次的操作
    long start = System.currentTimeMillis();
    for(int i = 0; i < 5000; i ++) {
        Connection connection = comboPooledDataSource.getConnection();  //这个方法就是从 DataSource 接口实现的
//            System.out.println("连接OK");
        connection.close();
    }
    long end = System.currentTimeMillis();
    System.out.println("使用c3p0 5000次连接mysql 耗时=" + (end - start)); //使用c3p0 5000次连接mysql 耗时=765
}

方式二:使用配置文件模板来完成

//方式2:使用配置文件模板来完成
//1.将c3p0提供的 c3p0-config.xml 拷贝到 src 目录下
//2.该文件指定了连接数据库和连接池的相关参数
@Test
public void testC3P0_02() throws Exception {

    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("jdbc_conn");

    Connection connection = comboPooledDataSource.getConnection();
    System.out.println("连接OK~");
    connection.close();
}

总结:使用c3p0连接池来连接数据库的效率远远好于传统方式。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值