该示例将通过手动初始化 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>
直接贴代码,不理解的地方查看注释。代码如下:
package com.hxstrive.jdbc_pool.c3p0;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* C3P0 简单应用
* @author hxstrive.com
*/
public class C3p0Hello {
   private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
   /**
    * 使用set方法配置C3P0
    */
   private static void configDataSource(){
       try {
           dataSource.setDriverClass("com.mysql.jdbc.Driver");
           dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false");
           dataSource.setUser("root");
           dataSource.setPassword("aaaaaa");
           // 连接初始化时创建的连接数
           dataSource.setInitialPoolSize(3);
           // 连接池中拥有的最大连接数,如果获得新的连接时,连接总数已满,则不会再获取新连接,而是等待其他连接释放
           dataSource.setMaxPoolSize(10);
           // 连接池保持的最小连接数
           dataSource.setMinPoolSize(3);
           // 连接池在无空闲连接可用时一次性创建的新数据库连接数
           dataSource.setAcquireIncrement(3);
       } catch (PropertyVetoException e) {
           e.printStackTrace();
       }
   }
   /**
    * 获取连接
    * @return
    */
   private static Connection getConnection(){
       Connection connection = null;
       // 配置数据源
       configDataSource();
       try {
           connection = dataSource.getConnection();
       } catch (SQLException e) {
           e.printStackTrace();
       }
       return connection;
   }
   public static void main(String[] args) throws Exception {
       Connection connection = null;
       PreparedStatement ps = null;
       ResultSet rs = null;
       try {
           connection = 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:40:24.0
