c3p0数据库连接池的简单使用

第一种,加载配置文件

    private static ComboPooledDataSource ds = null;
    static{
        //加载配置文件,得到数据库配置的一些信息
        Properties prop = new Properties();
        InputStream stream = JDBCUtil2.class.getResourceAsStream("/db.properties");
        try {
            prop.load(stream);
            ds = new ComboPooledDataSource();
            ds.setDriverClass(prop.getProperty("driverClassName"));
            ds.setJdbcUrl(prop.getProperty("url"));
            ds.setUser(prop.getProperty("username"));
            ds.setPassword(prop.getProperty("password"));
            ds.setCheckoutTimeout(3000);
            ds.setInitialPoolSize(5);
            ds.setMaxPoolSize(10);
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
    }
    public static Connection getConnection() throws Exception{
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new Exception("连接失败");
        }

    }

配置文件如下(可灵活编写):

url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
driverClassName=com.mysql.jdbc.Driver
maxWait=3000
initialSize=5
maxActive=10

第二种,也是加载配置文件(自动加载,然后直接获取连接对象就好但文件的名字一定要为c3p0-properties);

第三种,加载xml文件(自动加载,文件名要名为c3p0-config.xml)

如下

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
  <default-config>  
    <property name="user">root</property>
    <property name="password">123456</property>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
    <property name="initialPoolSize">5</property>
    <property name="checkoutTimeout">3000</property>
    <property name="maxPoolSize">10</property>
  </default-config>
 
  <named-config name="mySource">//
    <property name="user">root</property>
    <property name="password">123456</property>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
    <property name="initialPoolSize">5</property>
     <property name="checkoutTimeout">3000</property>
    <property name="maxPoolSize">15</property>
    <property name="minPoolSize">5</property>
  </named-config>
</c3p0-config>

 ComboPooledDataSource ds = new ComboPooledDataSource("mySource");

不指定mySource的话,默认使用default-config配置的
    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值