sunysh00 2020-04-26
c3p0使用过程:
通过ComboPooledDataSource获取数据源ds-->由数据源获取连接对象
导包
c3p0-0.9.1.2及以下的包不需要辅助包,高版本的需要对应的辅助包。
JDBC:加载驱动,由驱动连接数据库获取连接对象
c3p0:通过ComboPooledDataSource创建数据源,由数据源获取连接对象
? (即将加载驱动和连接数据库进行了封装)
public class C3p0{ public static DataSource ds = null; static{ ComboPooledDataSource cpds = new ComboPooledDataSource(); try{ cpds.setDriverClass("com.mysql.cj.jdbc.Driver"); cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/test?&useSSL=false&serverTimezone=UTC"); cpds.setUser("root"); cpds.setPassword("123"); cpds.setInitialPoolSize(5); cpds.setMaxPoolSize(15); ds = cpds; }catch(Exception e){ System.out.println("获取数据源失败!!!"); } } } //通过C3po.ds.getConnection()获取连接对象
.xml或.properties文件名命名:c3p0.properties/c3p0-config.xml
位置:在src目录下
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <!-- 默认 --> <default-config> <property name="driverClass">com.mysql.cj.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///test?useSSL=false&serverTimezone=UTC</property> <property name="user">root</property> <property name="password">123</property> <property name="checkoutTimeout">3000</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <!-- 自定义名称 <name-config name="名称"> <properties></properties> </name-config> --> </c3p0-config>
import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Test; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3p0Utils { private static DataSource ds = null; static{ ds = new ComboPooledDataSource(); } public static Connection getConn() { Connection conn = null; try { conn = ds.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } @Test public void Test(){ System.out.println(C3p0Utils.getConn()); } }