This topic introduces how to build an application by using a HikariCP connection pool, MySQL Connector/J, and OceanBase AI Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, data deletion, data updating, and data query.
Prerequisites
You have installed OceanBase AI Database and created a user tenant.
You have installed Java Development Kit (JDK) 1.8 and Maven.
You have installed Eclipse.
Note
The tool used to run the sample code in this topic is Eclipse IDE for Java Developers (2022-03), but you can also choose a tool that suits your personal preference to run the code.
Procedure
Note
The steps outlined in this topic are for the Windows environment. If you are using a different operating system or compiler, the steps may vary slightly.
- Import the
hikaricp-mysql-clientproject into Eclipse. - Obtain the URL of OceanBase AI Database.
- 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
Start Eclipse and choose File > Open Projects from File System.
In the dialog box that appears, click Directory to browse and select the project, and then click Finish.
Note
When you import a Maven project using Eclipse, it will automatically detect the
pom.xmlfile in the project, download the required dependency libraries based on the described dependencies in the file, and add them to the project.
View the project.

Step 2: Obtain the URL of OceanBase AI Database
Contact the deployment personnel or administrator of OceanBase AI Database to obtain the connection string.
Here is an example:
obclient -hxxx.xxx.xxx.xxx -P2881 -utest_user001@mysql001 -p****** -DtestFor more information about connection strings, see Connect to OceanBase AI Database by using OBClient.
Fill in the URL below based on the OceanBase AI Database connection string.
jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$password&useSSL=falseParameter description:
$hostspecifies the IP address for connecting to OceanBase AI Database. For connection through OceanBase Database Proxy (ODP), this parameter is the IP address of an ODP. For direct connection, this parameter is the IP address of an OBServer node.$portspecifies the port for connecting to OceanBase AI Database. For connection through ODP, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase AI Database is deployed.$database_namespecifies the name of the database to be accessed.Notice
The user used to connect to the tenant must have the
CREATE,INSERT,DELETE,UPDATE, andSELECTprivileges on the database. For more information about user privileges, see Privilege types in MySQL-compatible mode.$user_namespecifies the tenant account. For connection through ODP, the tenant account can be in theusername@tenant_name#cluster_nameorcluster_name:tenant_name:usernameformat. For direct connection, the tenant account is in theusername@tenant_nameformat.$passwordspecifies the password of the account.
For more information about the connection properties of MySQL Connector/J, see Configuration Properties.
Here is an example:
jdbc:mysql://xxx.xxx.xxx.xxx:2881/test?user=test_user001@mysql001&password=******&useSSL=false
Step 3: Modify the database connection information in the hikaricp-mysql-client project
Modify the database connection information in the hikaricp-mysql-client/src/main/resources/db.properties file based on the information obtained in Step 2.

Here is an example:
- The IP address of the OBServer node is
xxx.xxx.xxx.xxx. - The port is
2881. - The name of the database to be accessed is
test. - The tenant account is
test_user001@mysql001, wheremysql001is a user tenant created in OceanBase AI Database, andtest_user001is the username of themysql001tenant. - The password is
******.
The sample code is as follows:
...
jdbcUrl=jdbc:mysql://xxx.xxx.xxx.xxx:2881/test?useSSL=false
username=test_user001@mysql001
password=******
...
Step 4: Run the hikaricp-mysql-client project
In the project navigation view, locate 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's log information and output results.

You can also execute the following SQL statement in the 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 hikaricp-mysql-client to download the project code, which is a compressed file named hikaricp-mysql-client.zip.
After decompressing it, you will get 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 for source code.main: The main code directory, containing the application's primary logic.java: The Java source code directory.com: The Java package directory.example: The package directory for the sample project.Main.java: The main class sample file, containing logic for creating tables, and inserting, deleting, updating, and querying data.resources: The resource file directory, containing configuration files.db.properties: The connection pool configuration file, containing relevant database connection parameters.pom.xml: The Maven project configuration file, used to manage project dependencies and build settings.
Code in the pom.xml file
The pom.xml file is a configuration file for Maven projects, which defines the dependencies, plug-ins, and build rules of the projects. Maven is a Java project management tool that can automatically download dependencies, compile, and package the projects.
To configure the pom.xml file, perform the following steps:
Declare the file.
Declare the file to be an XML file that uses XML standard
1.0and character encodingUTF-8.The sample code is as follows:
<?xml version="1.0" encoding="UTF-8"?>Configure the namespaces and the POM model version.
xmlns: the default XML namespace, which is set tohttp://maven.apache.org/POM/4.0.0.xmlns:xsi: the namespace for XML elements prefixed withxsi, which is set tohttp://www.w3.org/2001/XMLSchema-instance.xsi:schemaLocation: the mapping between the XML namespace and its corresponding XML schema definition (XSD) file. The value typically consists of paired strings separated by spaces. Each pair consists of a default XML namespace (http://maven.apache.org/POM/4.0.0) in the first part, and the URI of the corresponding XSD file (http://maven.apache.org/xsd/maven-4.0.0.xsd) in the second part.<modelVersion>: the POM model version used by the POM file, which is set to4.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.
- Use
<groupId>to specify the project's organization ascom.example. - Use
<artifactId>to specify the project name ashikaricp-mysql-client. - Use
<version>to specify the project version as1.0-SNAPSHOT.
The sample code is as follows:
<groupId>com.example</groupId> <artifactId>hikaricp-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>- Use
Configure the properties of the project's source files.
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 also be compatible with the Java 8 runtime environment. This configuration ensures the project can correctly handle Java 8 syntax and features during compilation and runtime.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 to interact with the database:- Use
<groupId>to specify the dependency's organization asmysql. - Use
<artifactId>to specify the dependency name asmysql-connector-java. - Use
<version>to specify the dependency version as5.1.40.
The sample code is as follows:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency>- Use
Add the
HikariCPdependency library to implement a high-performance JDBC connection pool:- Use
<groupId>to specify the dependency's organization ascom.zaxxer. - Use
<artifactId>to specify the dependency name asHikariCP. - Use
<version>to specify the dependency version as3.3.1.
The sample code is as follows:
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.3.1</version> </dependency>- Use
Add the
logback-classicdependency library for convenient logging and management:- Use
<groupId>to specify the dependency's organization asch.qos.logback. - Use
<artifactId>to specify the dependency name aslogback-classic. - Use
<version>to specify the dependency version as1.2.5.
The sample code is as follows:
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.5</version> </dependency>- Use
Code in the db.properties file
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.
To configure the db.properties file, perform the following steps:
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=$passwordParameter description:
$hostspecifies the IP address for connecting to OceanBase AI Database. For connection through OceanBase Database Proxy (ODP), this parameter is the IP address of an ODP. For direct connection, this parameter is the IP address of an OBServer node.$portspecifies the port for connecting to OceanBase AI Database. For connection through ODP, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase AI Database is deployed.$database_namespecifies the name of the database to be accessed.$user_namespecifies the tenant account. For connection through ODP, the tenant account can be in theusername@tenant_name#cluster_nameorcluster_name:tenant_name:usernameformat. For direct connection, the tenant account is in theusername@tenant_nameformat.$passwordspecifies the password of the account.
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.
The following table describes the basic parameters of the 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 AI Database. | |
| username | N/A | The username for connecting to the database. | |
| password | N/A | The password for connecting to the database. | |
| Optional parameters | autoCommit | true | Controls the default auto-commit behavior of connections returned by the connection pool. |
| connectionTimeout | 30000 | Controls the maximum wait time for a client to obtain a connection from the connection pool. Unit: milliseconds. Default value is 30000 (30 seconds). The minimum acceptable connection timeout is 250 milliseconds. | |
| idleTimeout | 600000 | Controls the maximum idle time of a connection in the pool. Unit: milliseconds. Default value is 600000 (10 minutes). This setting has the following limitations:
|
|
| keepaliveTime | 0 | Controls the frequency of connection keepalives to prevent connections from being timed out by the database or network infrastructure. Unit: milliseconds. Default value is 0, which disables connection keepalives. This value must be less than the value of the maxLifetime attribute. |
|
| maxLifetime | 1800000 | Controls the maximum lifetime of a connection in the connection pool. Used connections are not automatically reclaimed; they are removed from the pool only when the connection is closed. Unit: milliseconds. Default value is 1800000 (30 minutes). Setting maxLifetime to 0 means there is no maximum lifetime limit for connections in the pool, i.e., the connection lifetime is infinite. |
|
| connectionTestQuery | N/A | The connection test query executed by the connection pool to the database. It is executed before a connection is acquired from the pool to verify that the database connection is still valid. | |
| minimumIdle | N/A | Controls the minimum number of idle connections maintained in the pool. If the number of idle connections falls below this value and the total number of connections in the pool is less than maximumPoolSize, HikariCP attempts to quickly and efficiently add additional connections. By default, the value of the minimumIdle attribute is the same as the maximumPoolSize attribute. |
|
| maximumPoolSize | 10 | Controls the maximum size allowed for the connection pool, including both idle and active connections. This value determines the maximum number of actual connections to the database backend. | |
| poolName | N/A | The user-defined name of the connection pool. This name is primarily used for identification and configuration management in logging and the JMX console. By default, a name is automatically generated. |
Code in the Main.java file
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.
To configure the Main.java file, perform the following steps:
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 the class and methods.
Define a Main class, with its
mainmethod serving as the program's entry point. In themainmethod, read thedb.propertiesfile to configure the HikariCP connection pool and obtain a database connection. Then, call a series of methods in sequence to create a table, insert data, query data, update data, and delete data. If anSQLExceptionexception occurs during the operations, the stack trace of the exception information will be 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 a method to create a table, passing the obtained database connection object, to create the
test_hikaricptable. - Call a method to insert data, passing the obtained database connection object and data parameters, to insert two rows of data:
(1,'A1')and(2,'A2'). - Call a method to query data, passing the obtained database connection object, to check the data insertion.
- Call a method to update data, passing the obtained database connection object and update parameters, to update the value in the
namecolumn of the row withid1totest_update. - Call a method to query data, passing the obtained database connection object, to check the data update.
- Call a method to delete data, passing the obtained database connection object and deletion parameters, to delete the row with
id2. - Call a method to query data, passing the obtained database connection object, to check the data deletion.
- If an
SQLExceptionexception occurs in thetryblock, print the exception's stack trace information. - Define methods for creating a table, 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 the method for creating a table. // Define the method for inserting data. // Define methods for querying data // Define a method for updating data. // Define a method for deleting data. }Define a method for creating a table.
Define a private static method
createTableto create a table namedtest_hikaricpin the database. This table contains anidcolumn and anamecolumn. The specific steps are as follows:- Define a private static method
createTable, which accepts a Connection object as a parameter and declares that it may throw anSQLExceptionexception. - Define an SQL statement string to create a table named
test_hikaricp, containing anidcolumn (data typeINT) and anamecolumn (data typeVARCHAR(50))). - Use the connection object
connto create a precompiled SQL statement objectpstmt, and use this object within atry-with-resourcesblock. - Execute the SQL statement to create the table named
test_hikaricp. - Print a message to the console indicating that the table has been created successfully.
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 named
insertDatato insert data into thetest_hikaricptable in the database. The specific steps are as follows:- Define a private static method named
insertData. This method accepts a Connection object, an integeridparameter, and a stringnameparameter, and declares that it may throw anSQLException. - Define an SQL statement string for inserting data into the table named
test_hikaricp, including theidandnamecolumns. - Create a precompiled SQL statement object
pstmtusing the connection objectconn, and use this object 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 the data has been inserted successfully.
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 named
Define a method for querying data.
Define a private static method named
selectDatato query data from thetest_hikaricptable in the database. The specific steps are as follows:- Define a private static method named
selectData. This method accepts a Connection object as a parameter and declares that it may throw anSQLException. - Define an SQL statement string to query all data from the table named
test_hikaricp. - Create a precompiled SQL statement object
pstmtusing the connection objectconn, and use this object within atry-with-resourcesblock. Also, execute the SQL query by calling theexecuteQuery()method and return the query result set 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 so, enter the loop. - Retrieve the value of the
idcolumn from the result set and assign it to the variableid. - Retrieve the value of the
namecolumn from the result set and assign it to the variablename. - Print the
idandnamevalues of each row of data to the console. - Print an empty line to 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 named
Define a method for updating data.
Define a private static method named
updateDatato update data in thetest_hikaricptable in the database. The specific steps are as follows:- Define a private static method named
updateData. This method accepts a Connection object, a stringnameparameter, and an integeridparameter, and declares that it may throw anSQLException. - Define an SQL statement string to update data in the table named
test_hikaricp. Update the value of thenamecolumn to the specifiednameif the value of theidcolumn equals the specifiedid. - Create a precompiled SQL statement object
pstmtusing the connection objectconn, and use this object 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 the data has been updated successfully.
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 named
Define a method for deleting data.
Define a private static method named
deleteDatato delete data that meets the specified conditions from thetest_hikaricptable in the database. The specific steps are as follows:- Define a private static method named
deleteData. This method accepts a Connection object and an integer parameterid, and declares that it may throw a SQLException exception. - Define an SQL statement string to delete data that meets the condition
id = ?from the table namedtest_hikaricp. - Use the connection object
connto create a precompiled SQL statement objectpstmt, and use this object within a try-with-resources block. - Set the value of the first parameter
?in the SQL statement toid. - Execute the SQL statement to delete the data that meets the conditions from the table.
- Print a message to the console indicating that the data has been deleted successfully.
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 named
Complete code examples
<?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 MySQL Connector/J, see Overview of MySQL Connector/J.
- For more information about the HikariCP connection pool, see HikariCP.
Download the hikaricp-mysql-client sample project