Sample program for connecting to an OceanBase database with a HikariCP connection pool
This topic describes how to use a HikariCP connection pool, MySQL Connector/J, and an OceanBase database to build an application. The application performs basic database operations, such as creating tables and inserting, deleting, updating, and querying data.
Download the hikaricp-mysql-client sample project
Prerequisites
You have installed OceanBase Database and created a MySQL mode tenant.
You have installed JDK 1.8 and Maven.
You have installed Eclipse.
NoteThis document uses Eclipse IDE for Java Developers 2022-03 to run the code. You can also use a different tool to run the sample code.
Procedure
The steps in this topic are for compiling and running the project in a Windows environment using Eclipse IDE for Java Developers 2022-03. The steps might differ slightly if you use a different operating system or compiler.
Import the
hikaricp-mysql-clientproject into Eclipse.Obtain the OceanBase database URL.
Modify the database connection information in the
hikaricp-mysql-clientproject.Run the
hikaricp-mysql-clientproject.
Step 1: Import the hikaricp-mysql-client project into Eclipse
Open Eclipse. In the menu bar, choose File -> Open Projects from File System.
In the dialog box that appears, click the Directory button to select the project directory. Then, click Finish to complete the import.
NoteWhen you import a Maven project into Eclipse, Eclipse automatically detects the
pom.xmlfile in the project. It then downloads the required dependency libraries based on the dependencies described in the file and adds them to the project.
View the project status.

Step 2: Obtain the OceanBase database URL
Contact the OceanBase database deployment staff or administrator to obtain the database connection string.
Example:
obclient -hxxx.xxx.xxx.xxx -P3306 -utest_user001 -p****** -DtestFor more information about connection strings, see Obtain connection parameters.
Use the information from the OceanBase database connection string to complete the following URL.
jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$password&useSSL=falseParameter description:
$host: The domain name for the OceanBase database connection.$port: The OceanBase database connection port. The default port for a MySQL mode tenant is 3306.$database_name: The name of the database to access.$user_name: The connection account for the tenant.$password: The password for the account.
For more information about MySQL Connector/J connection properties, see Configuration Properties.
Example:
jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?user=test_user001&password=******&useSSL=false
Step 3: Modify the database connection information in the hikaricp-mysql-client project
Use the information obtained in Step 2: Obtain the OceanBase database URL to modify the database connection information in the hikaricp-mysql-client/src/main/resources/db.properties file.
Example:
The IP address of the OBServer node is
xxx.xxx.xxx.xxx.The access port is 3306.
The name of the database to access is
test.The connection account for the tenant is
test_user001.The password is
******.
Code:
...
jdbcUrl=jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?useSSL=false
username=test_user001
password=******
...
Step 4: Run the hikaricp-mysql-client project
In the project navigator view, find and expand the src/main/java directory.
Right-click the Main.java file and choose Run As -> Java Application.
View the project logs and output results in the Eclipse console window.

You can also run the following SQL statement in the OceanBase client (OBClient) to view the result.
obclient [(none)]> SELECT * FROM test.test_hikaricp;The following result is returned:
+------+-------------+ | id | name | +------+-------------+ | 1 | test_update | +------+-------------+ 1 row in set
Project code overview
Click hikaricp-mysql-client to download the project code. The download is a compressed package named hikaricp-mysql-client.zip.
After you decompress the package, a folder named hikaricp-mysql-client is created. The directory structure is as follows:
hikaricp-mysql-client
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── Main.java
│ └── resources
│ └── db.properties
└── pom.xml
File description:
src: The root directory for the source code.main: The main code directory, which contains the main logic of the application.java: The Java source code directory.com: The Java package directory.example: The package directory for the sample project.Main.java: The main class file for the sample program. It contains the logic for creating tables and inserting, deleting, updating, and querying data.resources: The resource file directory, which contains configuration files.db.properties: The configuration file for the connection pool. It contains parameters related to the database connection.pom.xml: The configuration file for the Maven project. It is used to manage project dependencies and build settings.
pom.xml code overview
The pom.xml file is the configuration file for a Maven project. It defines information such as project dependencies, plugins, and build rules. Maven is a Java project management tool that can automatically download dependencies, compile, and package projects.
The pom.xml file in this topic mainly includes the following parts:
File declaration statement.
This statement declares that this file is an XML file, the XML version is
1.0, and the character encoding isUTF-8.Code:
<?xml version="1.0" encoding="UTF-8"?>Configure the POM namespace and POM model version.
xmlnsspecifies the POM namespace ashttp://maven.apache.org/POM/4.0.0.xmlns:xsispecifies the XML namespacehttp://www.w3.org/2001/XMLSchema-instance.xsi:schemaLocationspecifies the POM namespace ashttp://maven.apache.org/POM/4.0.0and the location of the POM's XSD file ashttp://maven.apache.org/xsd/maven-4.0.0.xsd.The
<modelVersion>element specifies that the POM model version used by this POM file is4.0.0.
Code:
<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"> <modelVersion>4.0.0</modelVersion> <!-- Other configurations --> </project>Configure basic information.
<groupId>specifies the project's organization ascom.example.<artifactId>specifies the project's name ashikaricp-mysql-client.<version>specifies the project's version number as1.0-SNAPSHOT.
Code:
<groupId>com.example</groupId> <artifactId>hikaricp-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>Configure project source file properties.
This section specifies the Maven compiler plugin as
maven-compiler-pluginand sets both the source and target Java versions to 8. This means the project's source code is written using Java 8 features, and the compiled bytecode will be compatible with the Java 8 runtime environment. This setting ensures that the project can correctly handle Java 8 syntax and features during compilation and runtime.NoteJava 1.8 and Java 8 are different names for the same version.
Code:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build>Configure project dependencies.
Add the
mysql-connector-javadependency library to interact with the database:<groupId>specifies the dependency's organization asmysql.<artifactId>specifies the dependency's name asmysql-connector-java.<version>specifies the dependency's version number as5.1.40.
Code:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency>Add the
HikariCPdependency library to implement a high-performance JDBC connection pool:<groupId>specifies the dependency's organization ascom.zaxxer.<artifactId>specifies the dependency's name asHikariCP.<version>specifies the dependency's version number as3.3.1.
Code:
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.3.1</version> </dependency>Add the
logback-classicdependency library for convenient log recording and management:<groupId>specifies the dependency's organization asch.qos.logback.<artifactId>specifies the dependency's name aslogback-classic.<version>specifies the dependency's version number as1.2.5.
Code:
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.5</version> </dependency>
db.properties code overview
db.properties is the connection pool configuration file for this sample. It contains the configuration properties for the connection pool. These properties include the database URL, username, password, and other optional connection pool settings.
The db.properties file in this topic mainly includes the following parts:
Configure database connection parameters.
Configure the database connection URL, including the host IP address, port number, and the database to access.
Configure the database username.
Configure the database password.
Code:
jdbcUrl=jdbc:mysql://$host:$port/$database_name?useSSL=false username=$user_name password=$passwordParameter explanation:
$host: The domain name for the OceanBase database connection.$port: The OceanBase database connection port. The default port for a MySQL mode tenant is 3306.$database_name: The name of the database to access.$user_name: The connection account for the tenant.$password: The password for the account.
Configure other connection pool parameters.
Enable the cache for precompiled SQL statements.
Set the cache size for precompiled SQL statements to 250.
Set the maximum lifecycle of a connection to 1,800,000 milliseconds (30 minutes). Connections that exceed this time are closed.
Set the idle timeout for a connection to 600,000 milliseconds (10 minutes). If a connection is idle for longer than this time, it is closed.
Set the connection timeout to 30,000 milliseconds (30 seconds). If a connection cannot be obtained within this time, an exception is thrown.
Code:
dataSource.cachePrepStmts=true dataSource.prepStmtCacheSize=250 dataSource.maxLifetime=1800000 dataSource.idleTimeout=600000 dataSource.connectionTimeout=30000
The specific property (parameter) configuration depends on your project requirements and database characteristics. Adjust the configuration as needed. For more information about HikariCP connection pool parameters, see Configuration.
Common basic parameters for HikariCP connection pools:
Category |
Parameter |
Default value |
Description |
Required parameters |
dataSourceClassName |
N/A |
Specifies the name of the DataSource class provided by the JDBC driver.
Important
Explicit configuration of |
jdbcUrl |
N/A |
Specifies the JDBC URL for connecting to the database. |
|
username |
N/A |
Specifies the username for connecting to the database. |
|
password |
N/A |
Specifies the password for connecting to the database. |
|
Common optional parameters |
autoCommit |
true |
Controls the default autocommit behavior of connections returned by the connection pool. |
connectionTimeout |
30000 |
Controls the maximum wait time for a client to obtain a connection from the pool. The unit is milliseconds. The default value is 30,000 (30 seconds). The minimum acceptable connection timeout is 250 milliseconds. |
|
idleTimeout |
600000 |
Controls the maximum time a connection can be idle in the pool. The unit is milliseconds. The default value is 600,000 (10 minutes). This setting has the following limitations:
|
|
keepaliveTime |
0 |
Controls the frequency of connection keepalive to prevent connections from being timed out by the database or network infrastructure. The unit is milliseconds. The default value is 0, which disables connection keepalive. This value must be less than the value of the |
|
maxLifetime |
1800000 |
Controls the maximum lifecycle of a connection in the connection pool. A connection that is in use is not automatically recycled. It is removed from the connection pool only when it is closed. The unit is milliseconds. The default value is 1,800,000 (30 minutes). If you set |
|
connectionTestQuery |
N/A |
Executes a connection test query that the connection pool sends to the database. It runs before a connection is obtained from the pool to verify that the connection to the database is still valid. |
|
minimumIdle |
N/A |
Controls the minimum number of idle connections maintained in the connection pool. If the number of idle connections falls below this value and the total number of connections in the pool is less than |
|
maximumPoolSize |
10 |
Controls the maximum size that the connection pool is allowed to reach, including both idle and in-use connections. This value determines the maximum number of actual connections to the database backend. |
|
poolName |
N/A |
Represents a user-defined name for the connection pool. This name is mainly used to identify the connection pool and its configuration in logging and JMX management consoles. By default, a name is automatically generated. |
Main.java code overview
The Main.java file is part of the sample program. It demonstrates how to obtain a database connection through a HikariCP connection pool and perform a series of database operations, including creating a table, inserting data, deleting data, updating data, querying data, and printing the query results.
The Main.java file in this topic mainly includes the following parts:
Import required classes and packages.
Define the package name of the current Java file as
com.exampleto organize and manage Java classes.Import the
java.sql.Connectionclass to establish and manage connections with the database.Import the
java.sql.PreparedStatementclass to execute precompiled SQL statements.Import the
java.sql.ResultSetclass to handle query result sets.Import the
java.sql.SQLExceptionclass to handle SQL exceptions.Import the
HikariConfigclass from HikariCP to configure the HikariCP connection pool.Import the
HikariDataSourceclass from HikariCP to create and manage the HikariCP connection pool.
Code:
package com.example; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource;Define the class name and methods.
This section defines a Main class, where the
mainmethod serves as the program's entry point. In themainmethod, the HikariCP connection pool is configured by reading thedb.propertiesfile, and a database connection is obtained. Then, a series of methods are called in sequence to create a table, insert data, query data, update data, and delete data. If aSQLExceptionoccurs during the operations, the exception's stack trace is printed. The specific steps are as follows:Define a public class named Main.
Define the entry method
mainfor the Main class.Create a HikariConfig object and configure it using the specified
db.propertiesfile.Create a HikariDataSource object and obtain a database connection within a
try-with-resourcesblock.Call the method for creating a table and pass the obtained database connection object to create the table
test_hikaricp.Call the method for inserting data and pass the database connection object and data parameters to insert two rows of data:
(1,'A1')and(2,'A2').Call the method for querying data and pass the database connection object to check the data insertion status.
Call the method for updating data and pass the database connection object and update parameters to update the value of the
namecolumn totest_updatein the row whereidis1.Call the method for querying data and pass the database connection object to check the data update status.
Call the method for deleting data and pass the database connection object and delete parameters to delete the row where
idis2.Call the method for querying data and pass the database connection object to check the data deletion status.
If a
SQLExceptionoccurs in thetryblock, the stack trace of the exception is printed.Define the methods for creating a table, inserting data, querying data, updating data, and deleting data.
Code:
public class Main { public static void main(String[] args) { try { HikariConfig config = new HikariConfig("/db.properties"); try (HikariDataSource dataSource = new HikariDataSource(config); Connection conn = dataSource.getConnection()) { createTable(conn); insertData(conn, 1, "A1"); insertData(conn, 2, "A2"); selectData(conn); updateData(conn, "test_update", 1); selectData(conn); deleteData(conn, 2); selectData(conn); } } catch (SQLException e) { e.printStackTrace(); } } // Define the method for creating a table // Define the method for inserting data // Define the method for querying data // Define the method for updating data // Define the method for deleting data }Define the method for creating a table.
This section defines a private static method
createTableto create a table namedtest_hikaricpin the database. The table contains anidcolumn and anamecolumn. The specific steps are as follows:Define a private static method
createTablethat accepts a Connection object as a parameter and declares that it may throw aSQLException.Define an SQL statement string to create a table named
test_hikaricp. The table contains anidcolumn (data typeINT) and anamecolumn (data typeVARCHAR(50)).Use the connection object
connto create a PreparedStatement objectpstmtand use it within atry-with-resourcesblock.Execute the SQL statement to create the table
test_hikaricp.Print a message to the console indicating that the table was created successfully.
Code:
private static void createTable(Connection conn) throws SQLException { String sql = "CREATE TABLE IF NOT EXISTS test_hikaricp (id INT, name VARCHAR(50))"; try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.executeUpdate(); System.out.println("Table created successfully."); } }Define the method for inserting data.
This section defines a private static method
insertDatato insert data into thetest_hikaricptable in the database. The specific steps are as follows:Define a private static method
insertDatathat accepts a Connection object, an integeridparameter, and a stringnameparameter, and declares that it may throw aSQLException.Define an SQL statement string to insert data into the
idandnamecolumns of thetest_hikaricptable.Use the connection object
connto create a PreparedStatement objectpstmtand use it within atry-with-resourcesblock.Set the value of the first parameter
?in the SQL statement toid.Set the value of the second parameter
?in the SQL statement toname.Execute the SQL statement to insert data into the table.
Print a message to the console indicating that data was inserted successfully.
Code:
private static void insertData(Connection conn, int id, String name) throws SQLException { String sql = "INSERT INTO test_hikaricp (id, name) VALUES (?, ?)"; try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, id); pstmt.setString(2, name); pstmt.executeUpdate(); System.out.println("Data inserted successfully."); } }Define the method for querying data.
This section defines a private static method
selectDatato query data from thetest_hikaricptable in the database. The specific steps are as follows:Define a private static method
selectDatathat accepts a Connection object as a parameter and declares that it may throw aSQLException.Define an SQL statement string to query all data from the
test_hikaricptable.Use the connection object
connto create a PreparedStatement objectpstmtand use it within atry-with-resourcesblock. At the same time, call theexecuteQuery()method to execute the SQL query and return a ResultSet objectrs.Print a message to the console indicating that user data is being printed.
Traverse the query result set. Use the
next()method to check if there is another row of data in the result set. If there is, the program enters the loop.Retrieve the value of the
idcolumn from the result set and assign it to theidvariable.Retrieve the value of the
namecolumn from the result set and assign it to thenamevariable.Print the
idandnamevalues of each row of data to the console.Print a blank line to the console.
Code:
private static void selectData(Connection conn) throws SQLException { String sql = "SELECT * FROM test_hikaricp"; try (PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery()) { System.out.println("User Data:"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } System.out.println(); } }Define the method for updating data.
This section defines a private static method
updateDatato update data in thetest_hikaricptable in the database. The specific steps are as follows:Define a private static method
updateDatathat accepts a Connection object, a stringnameparameter, and an integeridparameter, and declares that it may throw aSQLException.Define an SQL statement string to update data in the
test_hikaricptable. It updates the value of thenamecolumn to the specifiedname, where the value of theidcolumn equals the specifiedid.Use the connection object
connto create a PreparedStatement objectpstmtand use it within atry-with-resourcesblock.Set the value of the first parameter
?in the SQL statement toname.Set the value of the second parameter
?in the SQL statement toid.Execute the SQL statement to update the data in the table.
Print a message to the console indicating that data was updated successfully.
Code:
private static void updateData(Connection conn, String name, int id) throws SQLException { String sql = "UPDATE test_hikaricp SET name = ? WHERE id = ?"; try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, name); pstmt.setInt(2, id); pstmt.executeUpdate(); System.out.println("Data updated successfully."); } }Define the method for deleting data.
This section defines a private static method
deleteDatato delete data that meets a specific condition from thetest_hikaricptable in the database. The specific steps are as follows:Define a private static method
deleteDatathat accepts a Connection object and an integeridparameter, and declares that it may throw aSQLException.Define an SQL statement string to delete data from the
test_hikaricptable that meets the conditionid = ?.Use the connection object
connto create a PreparedStatement objectpstmtand use it within atry-with-resourcesblock.Set the value of the first parameter
?in the SQL statement toid.Execute the SQL statement to delete data that meets the condition from the table.
Print a message to the console indicating that data was deleted successfully.
Code:
private static void deleteData(Connection conn, int id) throws SQLException { String sql = "DELETE FROM test_hikaricp WHERE id = ?"; try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, id); pstmt.executeUpdate(); System.out.println("Data deleted successfully."); } }
Complete code
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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.oceanbase</groupId>
<artifactId>hikaricp-mysql-client</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
</project>
db.properties
jdbcUrl=jdbc:mysql://$host:$port/$database_name?useSSL=false
username=$user_name
password=$password
dataSource.cachePrepStmts=true
dataSource.prepStmtCacheSize=250
dataSource.maxLifetime=1800000
dataSource.idleTimeout=600000
dataSource.connectionTimeout=30000
Main.java
package com.example;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class Main {
public static void main(String[] args) {
try {
HikariConfig config = new HikariConfig("/db.properties");
try (HikariDataSource dataSource = new HikariDataSource(config);
Connection conn = dataSource.getConnection()) {
createTable(conn);
insertData(conn, 1, "A1");
insertData(conn, 2, "A2");
selectData(conn);
updateData(conn, "test_update", 1);
selectData(conn);
deleteData(conn, 2);
selectData(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void createTable(Connection conn) throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS test_hikaricp (id INT, name VARCHAR(50))";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.executeUpdate();
System.out.println("Table created successfully.");
}
}
private static void insertData(Connection conn, int id, String name) throws SQLException {
String sql = "INSERT INTO test_hikaricp (id, name) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.setString(2, name);
pstmt.executeUpdate();
System.out.println("Data inserted successfully.");
}
}
private static void selectData(Connection conn) throws SQLException {
String sql = "SELECT * FROM test_hikaricp";
try (PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
System.out.println("User Data:");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
System.out.println();
}
}
private static void updateData(Connection conn, String name, int id) throws SQLException {
String sql = "UPDATE test_hikaricp SET name = ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setInt(2, id);
pstmt.executeUpdate();
System.out.println("Data updated successfully.");
}
}
private static void deleteData(Connection conn, int id) throws SQLException {
String sql = "DELETE FROM test_hikaricp WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.executeUpdate();
System.out.println("Data deleted successfully.");
}
}
}
References
For more information about MySQL Connector/J, see Overview of MySQL Connector/J.
For more information about using a HikariCP connection pool, see HikariCP.