下面将通过一个简单示例演示 BoneCP 的基本用法,通过 JDBC 从 MySQL 5.7.* 中获取数据库时间戳。
pom.xml 文件内容:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <groupId>com.hxstrive.jdbc_pool</groupId> <version>1.0-SNAPSHOT</version> <modelVersion>4.0.0</modelVersion> <artifactId>bonecp</artifactId> <dependencies> <!-- https://mvnrepository.com/artifact/com.jolbox/bonecp --> <dependency> <groupId>com.jolbox</groupId> <artifactId>bonecp</artifactId> <version>0.8.0.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> </dependencies> </project>
下面没有使用 Spring 等框架,直接手动调用 BoneCP 的 API 配置数据库连接池。代码如下:
package com.hxstrive.jdbc_pool.bonecp;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* 从 BoneCP 中获取数据库连接,使用连接获取数据库时间戳。
* @author hxstrive.com
*/
public class BoneCpHello {
public static void main(String[] args) throws Exception {
// 1.加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.创建一个配置对象
BoneCPConfig config = new BoneCPConfig();
// 设置 JDBC url
config.setJdbcUrl("jdbc:mysql://localhost:3306/test?useSSL=false");
// 设置用户名
config.setUsername("root");
// 设置密码
config.setPassword("aaaaaa");
// 3.创建连接池
BoneCP connectionPool = new BoneCP(config);
// 4.获取当前数据库时间戳
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 5.获取一个连接
connection = connectionPool.getConnection();
ps = connection.prepareStatement("select CURRENT_TIMESTAMP() as ct");
rs = ps.executeQuery();
if(rs.next()) {
System.out.println(rs.getTimestamp("ct"));
}
} finally {
if(null != rs) {
rs.close();
}
if(null != ps) {
ps.close();
}
// 释放连接
if(null != connection) {
connection.close();
}
// 释放连接池
connectionPool.shutdown();
}
}
}运行示例,输出如下:
... SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. 2023-06-29 09:51:10.0 Process finished with exit code 0