C3P0 是成熟的 JDBC 連線池庫,支援連線重用、PreparedStatement 快取、自動回收閒置連線等功能。本工具類提供單例 DataSource 與兩種取得連線的方式,適合中小型專案快速整合。
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public final class JDBCUtils {
// 單例 DataSource,建議搭配 c3p0-config.xml 外部配置
private static final DataSource DATA_SOURCE = new ComboPooledDataSource();
private JDBCUtils() {} // 防止實例化
/** 取得 DataSource 實例(供框架如 Spring、MyBatis 注入使用) */
public static DataSource getDataSource() {
return DATA_SOURCE;
}
/** 手動取得一條連線(需自行關閉,歸還池中) */
public static Connection getConnection() throws SQLException {
return DATA_SOURCE.getConnection();
}
/** 關閉連線池(應用關閉時呼叫) */
public static void close() {
try {
((ComboPooledDataSource) DATA_SOURCE).close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">5</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
<property name="maxIdleTime">300</property>
<property name="checkoutTimeout">3000</property>
</default-config>
</c3p0-config>
// 方式一:手動管理連線(需 try-with-resources 確保關閉)
try (Connection conn = JDBCUtils.getConnection()) {
// 執行 SQL...
}
// 方式二:整合 Spring / MyBatis 時直接注入 DataSource
// @Bean public DataSource dataSource() { return JDBCUtils.getDataSource(); }
// 應用關閉時
Runtime.getRuntime().addShutdownHook(new Thread(JDBCUtils::close));
initialPoolSize:啟動時建立的連線數。minPoolSize / maxPoolSize:池中最小/最大連線數。maxIdleTime:連線閒置多少秒後被移除(秒)。checkoutTimeout:等待可用連線的最長時間(毫秒),超時拋出 SQLException。新專案建議考慮 HikariCP(Spring Boot 2.x 預設),效能更優、配置更簡潔。C3P0 適合維護舊專案或需特定 C3P0 功能(如 Statement 快取)的場合。