Skip to main content

HikariCP connection pool example with seekdb

This topic describes how to build an application by using HikariCP connection pool, MySQL Connector/J, and seekdb to perform basic database operations, including table creation, data insertion, data deletion, data updating, and data query.

Download the hikaricp-mysql-client sample project

Prerequisites

  • You have installed seekdb.

  • You have installed JDK 1.8 and Maven.

  • You have installed Eclipse.

    info

    The code in this topic is run in Eclipse IDE for Java Developers 2022-03. You can use any tool that you prefer.

Procedure

info

The following procedure describes how to compile and run the hikaricp-mysql-client project in Eclipse IDE for Java Developers 2022-03 on Windows. If you are using a different operating system or compiler, the procedure may vary slightly.

  1. Import the hikaricp-mysql-client project into Eclipse.
  2. Obtain the seekdb URL.
  3. Modify the database connection information in the hikaricp-mysql-client project.
  4. Run the hikaricp-mysql-client project.

Step 1: Import the hikaricp-mysql-client project into Eclipse

  1. Open Eclipse and select File > Open Projects from File System from the menu bar.

  2. In the dialog box that appears, click Directory to select the project directory, and then click Finish to complete the import.

    info

    When you import a Maven project into Eclipse, it automatically detects the pom.xml file in the project, downloads the required dependency libraries based on the described dependencies, and adds them to the project.

    1

  3. View the project.

    2

Step 2: Obtain the seekdb URL

  1. Contact the seekdb deployment personnel or administrator to obtain the database connection string.

    Example:

    mysql -hxxx.xxx.xxx.xxx -P2881 -uroot -p****** -Dtest

    For more information about the connection string, see Connect to seekdb by using a MySQL client.

  2. Fill in the corresponding information in the URL based on the seekdb connection string.

    jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$password&useSSL=false

    Parameter description:

    • $host: the IP address for connecting to seekdb. Replace it with the actual IP address. You can also use the local IP address or 127.0.0.1.
    • $port: the port for connecting to seekdb. Replace it with the actual port. The default port is 2881, which can be customized during seekdb deployment.
    • $database_name: the name of the database to be accessed.
    • user_name: the connection account. Format: username.
    • password: the password for the account.

    For more information about the MySQL Connector/J connection properties, see Configuration Properties.

    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: Obtain the seekdb URL.

3

Example:

  • The IP address of seekdb is xxx.xxx.xxx.xxx.
  • The access port is 2881.
  • The name of the database to be accessed is test.
  • The connection account is root.
  • The password is ******.

Code:

...
jdbcUrl=jdbc:mysql://xxx.xxx.xxx.xxx:2881/test?useSSL=false
username=root
password=******
...

Step 4: Run the hikaricp-mysql-client project

  1. In the Project Explorer view, locate and expand the src/main/java directory.

  2. Right-click the Main.java file and select Run As > Java Application.

    4

  3. View the project logs and output results in the Eclipse console window.

    5

  4. You can also execute the following SQL statement in seekdb to view the results.

    SELECT * FROM test.test_hikaricp;

    The returned 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 the file, you will find 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

File description:

  • src: the root directory for source code.
  • main: the main code directory, containing the core logic of the application.
  • java: the directory for Java source code.
  • com: the directory for Java packages.
  • example: the directory for packages in the sample project.
  • Main.java: the main class file, containing logic for creating tables, inserting, deleting, updating, and querying data.
  • resources: the directory for resource files, including configuration files.
  • db.properties: the configuration file for the connection pool, containing parameters related to database connections.
  • pom.xml: the configuration file for the Maven project, used to manage project dependencies and build settings.

Code introduction

The pom.xml file is the configuration file of a Maven project. It defines the dependencies, plugins, and build rules of the project. Maven is a Java project management tool that can automatically download dependencies, compile, and package projects.

The pom.xml file in this topic contains the following main sections:

  1. The file declaration statement.

    This statement declares that the file is an XML file using XML version 1.0 and character encoding UTF-8.

    Sample code:

    <?xml version="1.0" encoding="UTF-8"?>
  2. The POM namespace and model version.

    1. The xmlns attribute specifies the POM namespace as http://maven.apache.org/POM/4.0.0.
    2. The xmlns:xsi attribute specifies the XML namespace as http://www.w3.org/2001/XMLSchema-instance.
    3. The xsi:schemaLocation attribute specifies the POM namespace as http://maven.apache.org/POM/4.0.0 and the location of the POM XSD file as http://maven.apache.org/xsd/maven-4.0.0.xsd.
    4. The <modelVersion> element specifies the POM model version used by the POM file as 4.0.0.

    Sample 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>
  3. Basic information configuration.

    1. The <groupId> element specifies the project's group ID as com.example.
    2. The <artifactId> element specifies the project's artifact ID as hikaricp-mysql-client.
    3. The <version> element specifies the project's version as 1.0-SNAPSHOT.

    Sample code:

        <groupId>com.example</groupId>
    <artifactId>hikaricp-mysql-client</artifactId>
    <version>1.0-SNAPSHOT</version>
  4. Project source file properties configuration.

    The Maven compiler plugin is specified as maven-compiler-plugin, and the source and target Java versions are both set to 8. This means that 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 that the project can correctly handle Java 8 syntax and features during compilation and runtime.

    info

    Java 1.8 and Java 8 are different names for the same version.

    Sample 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>
  5. Project dependency component configuration.

    1. Add the mysql-connector-java dependency library for database interaction:

      1. The <groupId> element specifies the dependency's group ID as mysql.
      2. The <artifactId> element specifies the dependency's artifact ID as mysql-connector-java.
      3. The <version> element specifies the dependency's version as 5.1.40.

      Sample code:

              <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.40</version>
      </dependency>
    2. Add the HikariCP dependency library for high-performance JDBC connection pooling:

      1. The <groupId> element specifies the dependency's group ID as com.zaxxer.
      2. The <artifactId> element specifies the dependency's artifact ID as HikariCP.
      3. The <version> element specifies the dependency's version as 3.3.1.

      Sample code:

              <dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>HikariCP</artifactId>
      <version>3.3.1</version>
      </dependency>
    3. Add the logback-classic dependency library for convenient logging and management:

      1. The <groupId> element specifies the dependency's group ID as ch.qos.logback.
      2. The <artifactId> element specifies the dependency's artifact ID as logback-classic.
      3. The <version> element specifies the dependency's version as 1.2.5.

      Sample code:

              <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.5</version>
      </dependency>

Introduction to the db.properties file

db.properties is the connection pool configuration file in the example provided in this topic. It contains the configuration properties of the connection pool, including the database URL, username, password, and other optional parameters.

The code in the db.properties file in this topic mainly includes the following parts:

  1. Configure the database connection parameters.

    1. Configure the database connection URL, including the host IP, port number, and the database to be accessed.
    2. Configure the database username.
    3. Configure the database password.

    Sample code:

    jdbcUrl=jdbc:mysql://$host:$port/$database_name?useSSL=false
    username=$user_name
    password=$password

    Parameter description:

    • $host: the IP address for connecting to seekdb. Replace it with the actual IP address. You can also use the local IP address or 127.0.0.1.
    • $port: the port for connecting to seekdb. Replace it with the actual port number. The default value is 2881. You can customize it when you deploy seekdb.
    • $database_name: the name of the database to be accessed.
    • $user_name: the username for the connection. Format: username.
    • $password: the password for the account.
  2. Configure other parameters of the connection pool.

    1. Enable the cache for precompiled SQL statements.
    2. Set the cache size of the precompiled SQL statements to 250.
    3. Set the maximum lifetime of a connection to 1800000 milliseconds (30 minutes). After this period, the connection will be closed.
    4. Set the idle timeout of a connection to 600000 milliseconds (10 minutes). After this period, the connection will be closed if it is idle.
    5. Set the timeout of a connection to 30000 milliseconds (30 seconds). If no connection is obtained within this period, an exception will be thrown.

    Sample code:

    dataSource.cachePrepStmts=true
    dataSource.prepStmtCacheSize=250
    dataSource.maxLifetime=1800000
    dataSource.idleTimeout=600000
    dataSource.connectionTimeout=30000
info

The specific configuration of parameters depends on the project requirements and the characteristics of the database. We recommend that you adjust and configure the parameters based on your actual situation. For more information about the HikariCP connection pool parameters, see Configuration.

Common basic parameters of HikariCP connection pools:

CategoryParameterDefault valueDescription
Required parametersdataSourceClassNameN/AThe name of the DataSource class provided by the JDBC driver.
Notice:dataSourceClassName is usually not explicitly configured because HikariCP can automatically detect and load the appropriate driver.
Required parametersjdbcUrlN/AThe URL for connecting to the database through JDBC.
Required parametersusernameN/AThe username for connecting to the database.
Required parameterspasswordN/AThe password for connecting to the database.
Common optional parametersautoCommittrueControls the default auto-commit behavior of the connections returned by the connection pool
Common optional parametersconnectionTimeout30000Controls the maximum waiting time for a client to obtain a connection from the connection pool. The unit is milliseconds. The default value is 30000 (30 seconds). The minimum acceptable connection timeout is 250 milliseconds.
Common optional parametersidleTimeout600000Controls the maximum idle time of a connection in the pool. The unit is milliseconds. The default value is 600000 (10 minutes). This setting has the following limitations:
It takes effect only when minimumIdle is less than maximumPoolSize.
When the number of connections in the connection pool reaches minimumIdle, idle connections will not be recycled. Connections will only be recycled when the number of connections exceeds minimumIdle.
Common optional parameterskeepaliveTime0Controls 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, indicating that connection keepalive is disabled. This value must be less than the value of the maxLifetime parameter.
Common optional parametersmaxLifetime1800000Controls the maximum lifetime of a connection in the connection pool. Used connections will not be automatically recycled. They will be removed from the connection pool only when they are closed. The unit is milliseconds. The default value is 1800000 (30 minutes). If you set maxLifetime to 0, it indicates that there is no maximum lifetime limit for connections in the connection pool, meaning the connections have an infinite lifetime.
Common optional parametersconnectionTestQueryN/AExecutes a connection test query sent by the connection pool to the database. It is executed before obtaining a connection from the connection pool to verify whether the connection to the database is still valid.
Common optional parametersminimumIdleN/AControls the minimum number of idle connections to be maintained in the connection pool. If the number of idle connections is less than this value and the total number of connections in the connection pool is less than maximumPoolSize, HikariCP will try to add additional connections as quickly and efficiently as possible. By default, the value of the minimumIdle parameter is the same as that of the maximumPoolSize parameter.
Common optional parametersmaximumPoolSize10Controls the maximum size of the connection pool, including both idle and in-use connections. This value determines the maximum number of actual connections to the database backend.
Common optional parameterspoolNameN/AThe name of the user-defined connection pool. This name is mainly used for identifying the connection pool and its configuration in log records and the JMX management console. By default, a name will be automatically generated.

Main.java code introduction

The Main.java file is part of the sample program, which demonstrates how to obtain a database connection using the HikariCP connection pool and perform a series of database operations, including table creation, data insertion, data deletion, data update, and data query, and print the query results.

The Main.java file in this topic contains the following parts:

  1. Import the required classes and packages.

  2. Define the package name of the current Java file as com.example, which is used to organize and manage Java classes. 2. Import the java.sql.Connection class, which is used to establish and manage connections to the database. 3. Import the java.sql.PreparedStatement class, which is used to execute precompiled SQL statements. 4. Import the java.sql.ResultSet class, which is used to process query result sets. 5. Import the java.sql.SQLException class, which is used to handle SQL exceptions. 6. Import the HikariConfig class of HikariCP, which is used to configure the HikariCP connection pool. 7. Import the HikariDataSource class of HikariCP, which is used 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;
  1. Define the class name and method.

Define a Main class, whose main method serves as the program entry. In the main method, read the db.properties file to configure the HikariCP connection pool and obtain a database connection. Then, call a series of methods to create a table, insert data, query data, update data, and delete data. If an SQLException occurs during the operation, the exception stack trace is printed. The specific steps are as follows:

  1. Define a public class named Main. 2. Define the entry method main of the Main class. 3. Create a HikariConfig object and configure it using the specified db.properties file. 4. Create a HikariDataSource object and obtain a database connection in the try-with-resources block. 5. Call the method for creating a table and pass the obtained database connection object to create the test_hikaricp table. 6. Call the method for inserting data and pass the obtained database connection object and data parameters to insert two rows of data, (1,'A1') and (2,'A2'). 7. Call the method for querying data and pass the obtained database connection object to check the data insertion status. 8. Call the method for updating data and pass the obtained database connection object and update parameters to update the value of the name column in the row with id as 1 to test_update. 9. Call the method for querying data and pass the obtained database connection object to check the data update status. 10. Call the method for deleting data and pass the obtained database connection object and delete parameters to delete the row with id as 2. 11. Call the method for querying data and pass the obtained database connection object to check the data deletion status. 12. If an SQLException occurs in the try block, print the exception stack trace. 13. Define 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.
}
  1. Define the method for creating a table.

Define a private static method createTable to create a table named test_hikaricp in the database, which contains id and name columns. The specific steps are as follows:

  1. Define a private static method createTable that accepts a Connection object as a parameter and declares that it may throw an SQLException. 2. Define an SQL statement string to create a table named test_hikaricp with id (data type INT) and name (data type VARCHAR(50)) columns. 3. Use the connection object conn to create a precompiled SQL statement object pstmt and use it in the try-with-resources block. 4. Execute the SQL statement to create the test_hikaricp table. 5. Output 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.");
}
}
  1. Define the method for inserting data.

Define a private static method insertData to insert data into the test_hikaricp table in the database. The specific steps are as follows:

  1. Define a private static method insertData that accepts a Connection object, an integer id parameter, and a string name parameter, and declares that it may throw an SQLException. 2. Define an SQL statement string to insert data into the test_hikaricp table, including id and name columns. 3. Use the connection object conn to create a precompiled SQL statement object pstmt and use it in the try-with-resources block. 4. Set the value of the first parameter ? in the SQL statement to id. 5. Set the value of the second parameter ? in the SQL statement to name. 6. Execute the SQL statement to insert data into the table. 7. Output a message to the console indicating that the 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.");
}
}
  1. Define the method for querying data.

Define a private static method selectData to query data from the test_hikaricp table in the database. The specific steps are as follows:

  1. Define a private static method selectData that accepts a Connection object as a parameter and declares that it may throw an SQLException. 2. Define a SQL statement string for querying all data from the test_hikaricp table. 3. Use the conn connection object to create a precompiled SQL statement object pstmt, and use this object within a try-with-resources block. Execute the SQL query by calling the executeQuery() method and return the result set object rs. 4. Print a message to the console indicating that user data is being printed. 5. Traverse the query result set, use the next() method to check if there is another row of data in the result set, and enter the loop if there is. 6. Retrieve the value of the id column from the result set and assign it to the variable id. 7. Retrieve the value of the name column from the result set and assign it to the variable name. 8. Print the id and name values of each row to the console. 9. Print an empty line to the console.

Here is the 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();
}
}
  1. Define a method for updating data.

Define a private static method updateData for updating data in the test_hikaricp table in the database. The specific steps are as follows:

  1. Define a private static method updateData that accepts a Connection object, a string-type name parameter, and an integer-type id parameter, and declares that it may throw an SQLException. 2. Define a SQL statement string for updating data in the test_hikaricp table, setting the value of the name column to the specified name where the value of the id column equals the specified id. 3. Use the conn connection object to create a precompiled SQL statement object pstmt, and use this object within a try-with-resources block. 4. Set the value of the first parameter ? in the SQL statement to name. 5. Set the value of the second parameter ? in the SQL statement to id. 6. Execute the SQL statement to update the data in the table. 7. Print a message to the console indicating that the data update was successful.

Here is the 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.");
}
}
  1. Define a method for deleting data.

Define a private static method deleteData for deleting data from the test_hikaricp table in the database that meets the specified conditions. The specific steps are as follows:

  1. Define a private static method deleteData that accepts a Connection object and an integer-type id parameter, and declares that it may throw an SQLException. 2. Define a SQL statement string for deleting data from the test_hikaricp table where the value of the id column equals the specified id. 3. Use the conn connection object to create a precompiled SQL statement object pstmt, and use this object within a try-with-resources block. 4. Set the value of the first parameter ? in the SQL statement to id. 5. Execute the SQL statement to delete data from the table that meets the conditions. 6. Print a message to the console indicating that the data deletion was successful.

Here is the 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