This topic describes how to use a HikariCP connection pool, MySQL Connector/J, and OceanBase Cloud to build an application for basic database operations, such as table creation, data insertion, data deletion, data modification, and data query.
Download the hikaricp-mysql-client sample project Prerequisites
You have registered an OceanBase Cloud account and have created a cluster instance. For details, refer to Create a cluster instance.
You have obtained the connection string of the instance. For more information, see Obtain the connection string.
You have installed Java Development Kit (JDK) 1.8 and Maven.
You have installed Eclipse.
Note
This topic uses Eclipse IDE for Java Developers 2022-03 to run the sample code. You can also choose a suitable tool as needed.
Procedure
Note
The following procedure uses Eclipse IDE for Java Developers 2022-03 to compile and run this project in Windows. If you use another operating system or compiler, the procedure can be slightly different.
Step 1: Import the hikaricp-mysql-client project to Eclipse
Start Eclipse and choose File > Open Projects from File System.
In the dialog box that appears, click Directory, navigate to the directory where the project is located, and click Finish to import the project.
Note
When you use Eclipse to import a Maven project, Eclipse automatically detects the
pom.xmlfile in the project, downloads the required dependency libraries based on the dependencies described in the file, and adds them to the project.
View the project.

Step 2: Modify the database connection information in the hikaricp-mysql-client project
Modify the database connection information in the db.properties file in the hikaricp-mysql-client/src/main/resources/ directory based on the obtained connection string mentioned in the "Prerequisites" section.
Here is an example:
- The endpoint is
t5******.********.oceanbase.cloud. - The access port is
3306. - The name of the database to be accessed is
test. - The instance account is
test_user001. - The password is
******.
The sample code is as follows:
...
jdbcUrl=jdbc:mysql://t5******.********.oceanbase.cloud:3306/test?useSSL=false
username=test_user001
password=******
...
Step 3: Run the hikaricp-mysql-client project
In the project navigation view, find and expand the src/main/java directory.
Right-click the Main.java file and choose Run As > Java Application.

In the Console window of Eclipse, view the project logs and output results.

You can also execute the following SQL statement in OceanBase Client (OBClient) to view the results:
obclient [(none)]> SELECT * FROM test.test_hikaricp;The return result is as follows:
+------+-------------+ | id | name | +------+-------------+ | 1 | test_update | +------+-------------+ 1 row in set
Project code
Click here to download the project code, which is a package named hikaricp-mysql-client.zip.
Decompress the package to obtain a folder named hikaricp-mysql-client. The directory structure is as follows:
hikaricp-mysql-client
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── Main.java
│ └── resources
│ └── db.properties
└── pom.xml
The files and directories are described as follows:
src: the root directory that stores the source code.main: a directory that stores the main code, including the major logic of the application.java: a directory that stores the Java source code.com: a directory that stores the Java package.example: a directory that stores the packages of the sample project.Main.java: a sample file of themainclass that contains logic such as the table creation, data insertion, data deletion, data modification, and data query logic.resources: a directory that stores resource files, including configuration files.db.properties: the configuration file of the connection pool, which contains relevant database connection parameters.pom.xml: the configuration file of the Maven project, which is used to manage project dependencies and build settings.
Code in pom.xml
pom.xml is the configuration file of the Maven project, which defines the dependencies, plug-ins, and build rules of the project. Maven is a Java project management tool that can automatically download dependencies and compile and package projects.
Perform the following steps to configure the pom.xml file:
Declare the file.
Declare the file to be an XML file that uses XML standard 1.0 and the character encoding UTF-8.
The sample code is as follows:
<?xml version="1.0" encoding="UTF-8"?>Configure namespaces and the POM model version.
xmlns: the default XML namespace for the POM, which is set tohttp://maven.apache.org/POM/4.0.0.xmlns:xsi: the XML namespace for XML elements prefixed withxsi, which is set tohttp://www.w3.org/2001/XMLSchema-instance.xsi:schemaLocation: the location of an XML schema definition (XSD) file. The value consists of two parts: the default XML namespace(http://maven.apache.org/POM/4.0.0)and the URI of the XSD file (http://maven.apache.org/xsd/maven-4.0.0.xsd).<modelVersion>: the POM model version used by the POM file, which is set to 4.0.0.
The sample code is as follows:
<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>: the ID of the group to which the project belongs, which is set tocom.example.<artifactId>: the name of the project, which is set toproxool-mysql-client.<version>: the project version, which is set to1.0-SNAPSHOT.
The sample code is as follows:
<groupId>com.example</groupId> <artifactId>hikaricp-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>Configure the attributes of the project source file.
Specify
maven-compiler-pluginas the compiler plug-in of Maven, and set the source code version and target code version of the compiler to Java 8. This means that the project source code is compiled by using Java 8 and the compiled bytecode is compatible with the Java 8 runtime environment. This ensures that Java 8 syntax and characteristics can be correctly processed during the compilation and running of the project.Note
Java 1.8 and Java 8 are different names for the same version.
The sample code is as follows:
<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 the components on which the project depends.
Add the
mysql-connector-javadependency library for interactions with the database, and configure the following parameters:<groupId>: the ID of the group to which the dependency belongs, which is set tomysql.<artifactId>: the name of the dependency, which is set tomysql-connector-java.<version>: the version of the dependency, which is set to5.1.40.
The sample code is as follows:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency>Add the
HikariCPdependency library for implementing a high-performance JDBC connection pool, and configure the following parameters:<groupId>: the ID of the group to which the dependency belongs, which is set tocom.zaxxer.<artifactId>: the name of the dependency, which is set toHikariCP.<version>: the version of the dependency, which is set to3.3.1.
The sample code is as follows:
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.3.1</version> </dependency>Add the
logback-classicdependency library for log recording and management, and configure the following parameters:<groupId>: the ID of the group to which the dependency belongs, which is set toch.qos.logback.<artifactId>: the name of the dependency, which is set tologback-classic.<version>: the version of the dependency, which is set to1.2.5.
The sample code is as follows:
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.5</version> </dependency>
Code in db.properties
db.properties is a sample configuration file of the connection pool. The configuration file contains the URL, username, and password for connecting to the database, and other optional parameters of the connection pool.
Perform the following steps to configure the db.properties file:
Configure database connection parameters.
- Specify the URL for connecting to the database, including the host IP address, port number, and database to be accessed.
- Specify the username for connecting to the database.
- Specify the password for connecting to the database.
The sample code is as follows:
jdbcUrl=jdbc:mysql://$host:$port/$database_name?useSSL=false username=$user_name password=$passwordThe parameters are described as follows:
$host: the access address of OceanBase Cloud. The value is sourced from the-hparameter in the connection string.$port: the access port of OceanBase Cloud. The value is sourced from the-Pparameter in the connection string.$database_name: the name of the database to be accessed. The value is sourced from the-Dparameter in the connection string.$user_name: the account name. The value is sourced from the-uparameter in the connection string.$password: the account password. The value is sourced from the-pparameter in the connection string.
Configure other connection pool parameters.
- Enable caching for precompiled SQL statements.
- Set the cache size for precompiled SQL statements to 250.
- Set the maximum lifetime of connections to 1,800,000 ms (30 minutes). Connections exceeding the specified lifetime are closed.
- Set the timeout value of idle connections to 600,000 ms (10 minutes). Connections that have been idle for the specified period of time are closed.
- Set the timeout value for requesting a connection to 30,000 ms (30s). If no connection is obtained when the specified timeout value expires, an exception is thrown.
The sample code is as follows:
dataSource.cachePrepStmts=true dataSource.prepStmtCacheSize=250 dataSource.maxLifetime=1800000 dataSource.idleTimeout=600000 dataSource.connectionTimeout=30000
Notice
The actual parameter configurations depend on the project requirements and database characteristics. We recommend that you adjust and configure the parameters based on the actual situation. For more information about parameters of the HikariCP connection pool, see Configuration.
General parameters of a HikariCP connection pool
| Category | Parameter | Default value | Description |
|---|---|---|---|
| Required parameters | dataSourceClassName | N/A | The name of the DataSource class provided by the JDBC driver.
NoticeGenerally, the |
| jdbcUrl | N/A | The URL for the JDBC driver to connect to OceanBase Cloud. | |
| username | N/A | The username for connecting to the database. | |
| password | N/A | The password for connecting to the database. | |
| Optional parameters | autoCommit | true | Specifies whether to enable auto-commit for connections. |
| connectionTimeout | 30000 | The maximum waiting time when the client requests a connection from the connection pool, in ms. The default value is `30000`, indicating 30s. The minimum timeout value of connections is 250 ms. | |
| idleTimeout | 600000 | The maximum duration for which a connection can remain idle in the connection pool, in ms. The default value is `600000`, indicating 10 minutes. Observe the following limitations:
|
|
| keepaliveTime | 0 | The frequency for keeping a connection alive. This parameter prevents a connection from being timed out by the database or network infrastructure. The default value is `0`, which specifies to disable the connection keepalive feature. The value must be smaller than the value of maxLifetime. |
|
| maxLifetime | 1800000 | The maximum lifetime of a connection in the connection pool, in ms. Connections in use are not automatically recycled. A connection is removed from the connection pool only after it is closed. The default value is `1800000`, indicating 30 minutes. If you set maxLifetime to `0`, the lifetime of connections in the connection pool is unlimited. |
|
| connectionTestQuery | N/A | A query statement sent by the connection pool to the database for connection verification. When a connection is requested from the connection pool, this query statement is executed to verify whether the connection with the database is still valid. | |
| minimumIdle | N/A | The minimum number of idle connections in the connection pool. If the number of idle connections is smaller than the specified value and the total number of connections is smaller than the value of maximumPoolSize, HikariCP will add extra connections in a prompt and efficient way. By default, the values of minimumIdle and maximumPoolSize are the same. |
|
| maximumPoolSize | 10 | The maximum size of the connection pool, including the number of idle connections and the number of connections in use. This value determines the maximum number of actual connections with the database. | |
| poolName | N/A | The name of the connection pool. This name is used to identify the connection pool and its configurations in logs and the Java Management Extensions (JMX) management console. By default, a name is automatically generated for the connection pool. |
Code in Main.java
The Main.java file is a part of the sample application. It demonstrates the process of obtaining a database connection from the HikariCP connection pool, executing a series of database operations, such as table creation, data insertion, data deletion, data modification, and data query, and returning the query result.
Perform the following steps to configure the Main.java file:
Import the required classes and packages.
- Define the name of the Java package as
com.example, where the package is used for organizing and managing Java classes. - Import the
java.sql.Connectionclass for establishing and managing connections with the database. - Import the
java.sql.PreparedStatementclass for executing precompiled SQL statements. - Import the
java.sql.ResultSetclass for processing query result sets. - Import the
java.sql.SQLExceptionclass for handling SQL exceptions. - Import the
HikariConfigclass for configuring HikariCP connection pools. - Import the
HikariDataSourceclass for creating and managing HikariCP connection pools.
The sample code is as follows:
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 name of the Java package as
Define class names and methods.
Define a
Mainclass. Themainmethod serves as the entry to the application. Call themainmethod to read thedb.propertiesfile to configure the HikariCP connection pool and request database connections. Then, call a series of methods in sequence to create a table, insert data, query data, update data, and delete data. If anSQLExceptionoccurs during the operation, the stack trace of the exception is recorded. Perform the following steps:- Define a public class named
Main. - Define an entry method named
mainof theMainclass. - Create a
HikariConfigobject and configure the object based on thedb.propertiesfile. - Create a
HikariDataSourceobject and obtain a database connection by using thegetConnection()method in thetry-with-resourcesblock. - Call the table creation method and pass in the obtained database connection object to create a table named
test_hikaricp. - Call the data insertion method and pass in the obtained database connection object and data parameters to insert the
(1,'A1')and(2,'A2')records. - Call the data query method and pass in the obtained database connection object to query the inserted data.
- Call the data update method and pass in the obtained database connection object and update parameters to update the
namecolumn value of the row whoseidvalue is1totest_update. - Call the data query method and pass in the obtained database connection object to query the updated data.
- Call the data deletion method and pass in the obtained database connection object and deletion parameters to delete the row whose
idvalue is2. - Call the data query method and pass in the obtained database connection object to query the data after the deletion.
- If an
SQLExceptionoccurs in thetryblock, the stack trace of the exception is recorded. - Define methods for creating tables, inserting data, querying data, updating data, and deleting data.
The sample code is as follows:
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 a method for creating tables. // Define a method for inserting data. // Define a method for querying data. // Define a method for updating data. // Define a method for deleting data. }- Define a public class named
Define a method for creating tables.
Define a private static method
createTablefor creating a table namedtest_hikaricpin the database. The table contains theidandnamecolumns. Perform the following steps:- Define a private static method
createTablethat receives aConnectionobject as parameters, and declare that the method can throw anSQLException. - Define an SQL statement string for creating a table named
test_hikaricp. The table contains theidcolumn of theINTtype and thenamecolumn of theVARCHAR(50)type. - Create a precompiled SQL statement object
pstmtby using theConnectionobjectconnand use the object in thetry-with-resourcesblock. - Execute an SQL statement to create a table named
test_hikaricp. - If a success message is displayed in the console, the table is successfully created.
The sample code is as follows:
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 a private static method
Define a method for inserting data.
Define a private static method
insertDatafor inserting data into thetest_hikaricptable in the database. Perform the following steps:- Define a private static method
insertDatathat receives aConnectionobject, anidparameter of the integer type, and anameparameter of the string type, and declare that the method can throw anSQLException. - Define an SQL statement string for inserting the
idandnamecolumns into thetest_hikaricptable. - Create a precompiled SQL statement object
pstmtby using theConnectionobjectconnand use the object in thetry-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.
- If a success message is displayed in the console, the data is successfully inserted into the table.
The sample code is as follows:
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 a private static method
Define a method for querying data.
Define a private static method
selectDatafor querying data from thetest_hikaricptable in the database. Perform the following steps:- Define a private static method
selectDatathat receives aConnectionobject as parameters, and declare that the method can throw anSQLException. - Define an SQL statement string for querying all data in the
test_hikaricptable. - Create a precompiled SQL statement object
pstmtby using theConnectionobjectconnand use the object in thetry-with-resourcesblock. Call theexecuteQuery()method to execute an SQL query and return the query result set objectrs. - If a message is displayed in the console, user data is being returned.
- Traverse the query result set. Call the
next()method to check whether a next row exists in the result set. If yes, a loop begins. - Obtain the values of the
idcolumn from the result set and assign them to theidvariable. - Obtain the values of the
namecolumn from the result set and assign them to thenamevariable. - Return the
idandnamevalues of each row in the console. - Return an empty row in the console.
The sample code is as follows:
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 a private static method
Define a method for updating data.
Define a private static method
updateDatafor updating data in thetest_hikaricptable in the database. Perform the following steps:- Define a private static method
updateDatathat receives aConnectionobject, anidparameter of the integer type, and anameparameter of the string type, and declare that the method can throw anSQLException. - Define an SQL statement string for updating the value of the
namecolumn in the row whoseidcolumn value equals the specifiedidvalue in thetest_hikaricptable to the specified name value. - Create a precompiled SQL statement object
pstmtby using theConnectionobjectconnand use the object in thetry-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 data in the table.
- If a success message is displayed in the console, the data is successfully updated.
The sample code is as follows:
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 a private static method
Define a method for deleting data.
Define a private static method
deleteDatafor deleting data that meets the specified condition from thetest_hikaricptable in the database. Perform the following steps:- Define a private static method
deleteDatathat receives aConnectionobject and anidparameter of the integer type, and declare that the method can throw anSQLException. - Define an SQL statement string for deleting data that meets the
id = ?condition from thetest_hikaricptable. - Create a precompiled SQL statement object
pstmtby using theConnectionobjectconnand use the object in thetry-with-resourcesblock. - Set the value of the first parameter
?in the SQL statement toid. - Execute the SQL statement to delete data that meets the specified condition from the table.
- If a success message is displayed in the console, the data is successfully deleted.
The sample code is as follows:
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."); } }- Define a private static method
Complete code
<?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>
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
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 the HikariCP connection pool, see HikariCP.