下面直接通过 Java 代码使用 HikariCP 数据库连接池连接到 MySQL 数据并获取一个数据库连接,通过该连接获取当前数据库的时间戳。
JDK版本:1.8
MySQL版本:5.7.*
将下面依赖信息添加到 pom.xml 文件:
<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP --> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>4.0.3</version> </dependency> <!-- 数据库驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>
下面代码通过 HikariConfig 配置数据库连接池,然后手动 new 一个 HikariDataSource 对象,然后使用 DataSource 的 getConnection() 方法获取数据库连接。代码如下:
package com.hxstrive.jdbc_pool.HikariCP; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * HikariCP 简单用法 * @author hxstrive.com */ public class HikariCPHello { public static void main(String[] args) throws Exception { HikariConfig config = new HikariConfig(); config.setDriverClassName("com.mysql.jdbc.Driver"); config.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false"); config.setUsername("root"); config.setPassword("aaaaaa"); config.addDataSourceProperty("cachePrepstmts", "true"); config.addDataSourceProperty("prepstmtCachesize", "250"); config.addDataSourceProperty("prepstmtCacheSqlLimit", "2048"); Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { DataSource dataSource = new HikariDataSource(config); 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-11 12:33:45.0