掌握c3p0

2. 路径
1. c3p0 介绍
2. c3p0 的使⽤ ( 硬编码 )
3. c3p0 的使⽤ ( 配置⽂件 )
4. 编写 C3P0Util ⼯具类
3. 讲解
3.1 c3p0 介绍 C3P0 开源免费的连接池!⽬前使⽤它的开源项⽬有:
Spring Hibernate 等。使⽤第三⽅⼯具需要导⼊ jar 包,
c3p0 使⽤时还需要添加配置⽂件 c3p0-config.xml.
使⽤ C3P0 需要添加 c3p0-0.9.1.2.jar
3.2c3p0 的使⽤
3.2.1 通过硬编码来编写【了解】
步骤
1. 拷⻉ jar
2. 创建 C3P0 连接池对象
3. C3P0 连接池对象⾥⾯获得 connection
导入jar包
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>

创建工具类

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;

public class C3P0Util {
    /**
     * 包名:com.sunlw.utils
     *
     * @author sunlw
     * ⽇期2020-07-06 11:43
     * 这个⼯具类就负责,提供C3P0连接池对象
     */
    private static DataSource dataSource;

    static {
        dataSource = new ComboPooledDataSource();
    }

    /**
     * 获取连接池
     *
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }
}

resources下创建c3p0-config.xml

<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/2207b</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        <property name="initialPoolSize">5</property>
    </default-config>
</c3p0-config>

代码运行

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

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

public class c3p0Date {
    @Test
    public void c3p0show() throws PropertyVetoException, SQLException {
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/2207b");
        cpds.setUser("root");
        cpds.setPassword("123456");
        Connection connection = cpds.getConnection();
        System.out.println(connection);
    }
    @Test
    public void c3p0show2() throws SQLException {
        DataSource dataSource = C3P0Util.getDataSource();
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值