C3P0数据源的使用(一)

使用C3P0数据源便捷得到Connection

作用:便捷的创建一个连接池并且获得Connect连接

前提:

  1. 需要导入c3p0-0.9.1.2.jar和mysql-connector-java-5.1.7-bin.jar两个包
  2. 自己写好连接池以及数据库的配置信息c3p0-config.xml

测试的整体结构:
测试结构

放在src下的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://localhost:3306/day13</property>
        <property name="user">root</property>
        <property name="password">etron</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>



    </default-config>



</c3p0-config>

C3P0Util.java

package com.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class C3P0Util {
    //得到一个数据源
    private static DataSource dataSource = new ComboPooledDataSource();

    //从数据源中得到有个连接对象
    public static Connection getConnection(){
        try{
            return dataSource.getConnection();
        }catch (SQLException e){
            throw new RuntimeException("服务器错误");
        }
    }

    public static void release(Connection conn, Statement stmt, ResultSet rs){
        if(rs!=null){
            try{
                rs.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        if(stmt!=null){
            try{
                stmt.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try{
                conn.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}

TestCRUD.java

package com.util;

import java.sql.Connection;
import java.sql.PreparedStatement;

public class TestCRUD {

    public static void main(String[] args){
        new TestCRUD().test1();
    }
    public void test1(){
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Util.getConnection();
            ps = conn.prepareStatement("insert into account(name,money) values('ggg',2000) ");
            ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            C3P0Util.release(conn,ps,null);
        }
        System.out.println(conn.getClass().getName());
    }
}

控制台打印的结果
控制台打印

猜你喜欢

转载自blog.csdn.net/weixin_42036647/article/details/82951388