c3p0连接数据库



package com.c3p0;
import java.sql.Connection;
import javax.sql.DataSource;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;


public class JDBC {
 private static DataSource dataSource = null;

 // 数据库连接池只需初始化一次
 static {
  dataSource = new ComboPooledDataSource("helloc3p0");
 }

 public static Connection getConnection() throws Exception {
  return dataSource.getConnection();
 }

 /**
  * 准备mysql-connector jar和c3p0 jar包
  * 1.创建c3p0-config.xml 文件
  * 2.创建ComboPooledDataSource实例
  * DataSource dataSource =
    new ComboPooledDataSource("helloc3p0");
     3.从DataSource实例中获取数据库连接。
  * @throws Exception
  */
 

 @Test
 public void testC3p0WithConfigFile() throws Exception{
  DataSource dataSource =
    new ComboPooledDataSource("helloc3p0");
  System.out.println(dataSource.getConnection());
  
  
 }

 @Test
 public void testC3P0() throws Exception{
  ComboPooledDataSource cpds = new ComboPooledDataSource();
  cpds.setDriverClass("com.mysql.jdbc.Driver");
  cpds.setJdbcUrl("jdbc:mysql:///jdbc");
  cpds.setUser("root");
  cpds.setPassword("mysql");
  
  System.out.println(cpds.getConnection());
  
 }
 
}


c3p0配置文件:

<c3p0-config>
 <named-config name="helloc3p0">

  <!-- 指定连接数据源的基本属性 -->
  <property name="user">root</property>
  <property name="password">mysql</property>
  <property name="driverClass">com.mysql.jdbc.Driver</property>
  <property name="jdbcUrl">jdbc:mysql:///jdbc</property>

  <!-- 若数据库中连接数不足时,一次向数据库服务器申请多少个连接 -->
  <property name="acquireIncrement">5</property>
  <!-- 初始化数据库连接池时连接的数量 -->
  <property name="initialPoolSize">5</property>
  <!-- 数据库连接池中的最小的数据库连接数 -->
  <property name="minPoolSize">5</property>
  <!-- 数据库连接池中的最大的数据库连接数 -->
  <property name="maxPoolSize">10</property>

  <!-- C3P0数据库连接池可以维护的Statement的个数 -->
  <property name="maxStatements">20</property>
  <!-- 每个连接同时可以使用的Statement 对象的个数 -->
  <property name="maxStatementsPerConnection">5</property>
 </named-config>
</c3p0-config>




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值