1702-MySQL-C3P0连接池实例


1.配置

加载c3p0-0.9.1.2.jar包
设置c3p0-config.xml 配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 默认配置 -->
  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql:///test</property>
    <property name="user">root</property>
    <property name="password">root</property>
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">20</property>
  </default-config>

  <named-config name="oracle"> 
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql:///test</property>
    <property name="user">root</property>
    <property name="password">root</property>
  </named-config> 
  </c3p0-config>

2,Test

package com.it.jdbc.TestDataSoure;

import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;
import com.it.jdbc.DataSoure.MyDataSoure;
import com.it.jdbc.utils.C3P0Utils;
import com.it.jdbc.utils.JDBCUtils_V3;

public class TestC3P0 {
    @Test
    public void testAdduser1() {
    Connection conn = null;
    PreparedStatement pstmt = null;
    // 自定义连接池对象
    try {
        // 从连接池获得链接
        conn = C3P0Utils.getConnection();
        String sql = "insert into use1 value(null,?,?)";
        pstmt =conn.prepareStatement(sql);
        pstmt.setString(1, "何一");
        pstmt.setString(2, "李二");
        int rows = pstmt.executeUpdate();
        if (rows > 0) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        JDBCUtils_V3.release(conn, pstmt, null);
    }
}
}

3.添加工具类C3P0Utils:

package com.it.jdbc.utils;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {
        private static ComboPooledDataSource dataSoure = new ComboPooledDataSource();//默认配置,classpath目录下
        //ComboPooledDataSource pool = new ComboPooledDataSource("hh")
        //或加载“c3p0-config.xml”的配置元素"hh"
         for(int i=0;i<25;i++){

        private static DataSource getDataSource(){
            return dataSoure;
        }
        public static Connection getConnection(){
            try {
                return dataSoure.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException();
            }
        }
}

凌晨记

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值