该示例将通过配置文件的方式去初始化 C3P0 的 ComboPooledDataSource 数据源,然后从数据源中获取一个连接,使用该连接获取 MySQL 数据库的当前时间戳。
JDK版本:1.8
MySQL版本:5.7.*
由于本项目采用 Maven 管理依赖,所以直接在 pom.xml 文件中添加如下依赖:
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- 数据库驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>
直接贴代码,不理解的地方查看注释。
在项目的 resouces 目录创建 c3p0-config.xml 配置文件(注意:配置文件名称必须为 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/test?useUnicode=true&characterEncoding=utf8&useSSL=false</property> <property name="user">root</property> <property name="password">aaaaaa</property> <property name="checkoutTimeout">30000</property> <property name="idleConnectionTestPeriod">30</property> <property name="initialPoolSize">3</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">2</property> <property name="maxStatements">200</property> </default-config> </c3p0-config>
package com.hxstrive.jdbc_pool.c3p0;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* 通过配置文件配置 C3P0 数据源
* @author hxstrive.com
*/
public class C3p0ForCfgFile {
// 使用默认配置连接
public static ComboPooledDataSource dataSource = new ComboPooledDataSource();
public static void main(String[] args) throws Exception {
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 获取连接
connection = dataSource.getConnection();
// 查询数据库当前时间戳
ps = connection.prepareStatement("select CURRENT_TIMESTAMP() as ct");
rs = ps.executeQuery();
if(rs.next()) {
System.out.println(rs.getTimestamp("ct"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null != rs) {
rs.close();
}
if(null != ps) {
ps.close();
}
// 释放连接
if(null != connection) {
connection.close();
}
}
}
}运行代码输出如下:
2023-07-04 12:57:49.0