1702-MySQL-C3P0连接池实例

来源:互联网 发布:java document类 编辑:程序博客网 时间:2024/06/03 23:45

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();            }        }}

凌晨记

原创粉丝点击