Sample program for connecting to an OceanBase database with a HikariCP connection pool

更新时间:
复制 MD 格式

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.

image.pngDownload 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.

    Note

    This 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

Note

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.

  1. Import the hikaricp-mysql-client project into Eclipse.

  2. Obtain the OceanBase database 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. In the menu bar, choose File -> Open Projects from File System.

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

    Note

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

    image.png

  3. View the project status.

    image.png

Step 2: Obtain the OceanBase database URL

  1. Contact the OceanBase database deployment staff or administrator to obtain the database connection string.

    Example:

    obclient -hxxx.xxx.xxx.xxx -P3306 -utest_user001 -p****** -Dtest

    For more information about connection strings, see Obtain connection parameters.

  2. 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=false
    

    Parameter 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

  1. In the project navigator view, find and expand the src/main/java directory.

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

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

    image.png

  4. 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:

  1. File declaration statement.

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

    Code:

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

    1. xmlns specifies the POM namespace as http://maven.apache.org/POM/4.0.0.

    2. xmlns:xsi specifies the XML namespace http://www.w3.org/2001/XMLSchema-instance.

    3. xsi:schemaLocation specifies the POM namespace as http://maven.apache.org/POM/4.0.0 and the location of the POM's XSD file as http://maven.apache.org/xsd/maven-4.0.0.xsd.

    4. The <modelVersion> element specifies that the POM model version used by this POM file is 4.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>
    
  3. Configure basic information.

    1. <groupId> specifies the project's organization as com.example.

    2. <artifactId> specifies the project's name as hikaricp-mysql-client.

    3. <version> specifies the project's version number as 1.0-SNAPSHOT.

    Code:

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

    This section specifies the Maven compiler plugin as maven-compiler-plugin and 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.

    Note

    Java 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>
    
  5. Configure project dependencies.

    1. Add the mysql-connector-java dependency library to interact with the database:

      1. <groupId> specifies the dependency's organization as mysql.

      2. <artifactId> specifies the dependency's name as mysql-connector-java.

      3. <version> specifies the dependency's version number as 5.1.40.

      Code:

              <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
                  <version>5.1.40</version>
              </dependency>
    2. Add the HikariCP dependency library to implement a high-performance JDBC connection pool:

      1. <groupId> specifies the dependency's organization as com.zaxxer.

      2. <artifactId> specifies the dependency's name as HikariCP.

      3. <version> specifies the dependency's version number as 3.3.1.

      Code:

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

      1. <groupId> specifies the dependency's organization as ch.qos.logback.

      2. <artifactId> specifies the dependency's name as logback-classic.

      3. <version> specifies the dependency's version number as 1.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:

  1. Configure database connection parameters.

    1. Configure the database connection URL, including the host IP address, port number, and the database to access.

    2. Configure the database username.

    3. Configure the database password.

    Code:

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

    Parameter 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.

  2. Configure other connection pool parameters.

    1. Enable the cache for precompiled SQL statements.

    2. Set the cache size for precompiled SQL statements to 250.

    3. Set the maximum lifecycle of a connection to 1,800,000 milliseconds (30 minutes). Connections that exceed this time are closed.

    4. 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.

    5. 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
Important

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 dataSourceClassName is usually not required because HikariCP can automatically detect and load the appropriate driver.

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:

  • This setting is effective only when minimumIdle is less than maximumPoolSize.

  • Idle connections are not recycled if the number of connections in the pool is at the minimumIdle level. Connections are recycled only if the connection count exceeds minimumIdle.

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 property.

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 maxLifetime to 0, connections have no maximum lifecycle limit in the pool, meaning their lifecycle is infinite.

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, HikariCP tries to add extra connections quickly and efficiently. By default, the value of the minimumIdle property is the same as the maximumPoolSize property.

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:

  1. Import required classes and packages.

    1. Define the package name of the current Java file as com.example to organize and manage Java classes.

    2. Import the java.sql.Connection class to establish and manage connections with the database.

    3. Import the java.sql.PreparedStatement class to execute precompiled SQL statements.

    4. Import the java.sql.ResultSet class to handle query result sets.

    5. Import the java.sql.SQLException class to handle SQL exceptions.

    6. Import the HikariConfig class from HikariCP to configure the HikariCP connection pool.

    7. Import the HikariDataSource class 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;
  2. Define the class name and methods.

    This section defines a Main class, where the main method serves as the program's entry point. In the main method, the HikariCP connection pool is configured by reading the db.properties file, 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 a SQLException occurs during the operations, the exception's stack trace is printed. The specific steps are as follows:

    1. Define a public class named Main.

    2. Define the entry method main for 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 within a try-with-resources block.

    5. Call the method for creating a table and pass the obtained database connection object to create the table test_hikaricp.

    6. 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').

    7. Call the method for querying data and pass the database connection object to check the data insertion status.

    8. Call the method for updating data and pass the database connection object and update parameters to update the value of the name column to test_update in the row where id is 1.

    9. Call the method for querying data and pass the database connection object to check the data update status.

    10. Call the method for deleting data and pass the database connection object and delete parameters to delete the row where id is 2.

    11. Call the method for querying data and pass the database connection object to check the data deletion status.

    12. If a SQLException occurs in the try block, the stack trace of the exception is printed.

    13. 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
    }
  3. Define the method for creating a table.

    This section defines a private static method createTable to create a table named test_hikaricp in the database. The table contains an id column and a name column. 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 a SQLException.

    2. Define an SQL statement string to create a table named test_hikaricp. The table contains an id column (data type INT) and a name column (data type VARCHAR(50)).

    3. Use the connection object conn to create a PreparedStatement object pstmt and use it within a try-with-resources block.

    4. Execute the SQL statement to create the table test_hikaricp.

    5. 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.");
            }
        }
  4. Define the method for inserting data.

    This section defines 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 a SQLException.

    2. Define an SQL statement string to insert data into the id and name columns of the test_hikaricp table.

    3. Use the connection object conn to create a PreparedStatement object pstmt and use it within a 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. 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.");
            }
        }
  5. Define the method for querying data.

    This section defines 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 a SQLException.

    2. Define an SQL statement string to query all data from the test_hikaricp table.

    3. Use the connection object conn to create a PreparedStatement object pstmt and use it within a try-with-resources block. At the same time, call the executeQuery() method to execute the SQL query and return a ResultSet 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. If there is, the program enters the loop.

    6. Retrieve the value of the id column from the result set and assign it to the id variable.

    7. Retrieve the value of the name column from the result set and assign it to the name variable.

    8. Print the id and name values of each row of data to the console.

    9. 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();
            }
        }
  6. Define the method for updating data.

    This section defines a private static method updateData to update 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 name parameter, and an integer id parameter, and declares that it may throw a SQLException.

    2. Define an SQL statement string to update data in the test_hikaricp table. It updates the value of the name column to the specified name, where the value of the id column equals the specified id.

    3. Use the connection object conn to create a PreparedStatement object pstmt and use it 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 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.");
            }
        }
  7. Define the method for deleting data.

    This section defines a private static method deleteData to delete data that meets a specific condition from the test_hikaricp table in the database. The specific steps are as follows:

    1. Define a private static method deleteData that accepts a Connection object and an integer id parameter, and declares that it may throw a SQLException.

    2. Define an SQL statement string to delete data from the test_hikaricp table that meets the condition id = ?.

    3. Use the connection object conn to create a PreparedStatement object pstmt and use it 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 that meets the condition from the table.

    6. 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