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

Step 2: Get the OceanBase database URL
Contact the OceanBase database deployment personnel or administrator to obtain the database connection string.
Example:
obclient -hxxx.xxx.xxx.xxx -P3306 -utest_user001 -p****** -DtestFor more information about connection strings, see Get connection parameters.
Use the information from the OceanBase database connection string to populate the following URL.
jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$passwordParameter 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 tenant's connection account.$password: The account password.
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=******
Step 3: Modify the database connection information in the dbcp-mysql-client project
Modify the database connection information in the dbcp-mysql-client/src/main/resources/db.properties file using the information from Step 2: Obtain the OceanBase database URL.
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 tenant's connection account is
test_user001.The password is
******.
Code:
...
url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/test
username=test_user001
password=******
...
Step 4: Run the dbcp-mysql-client project
In the Project Explorer view, find and expand the src/main/java directory.
Right-click the Main.java file and choose Run As > Java Application.
View the project's log information and output results in the Eclipse console window.

You can also run the following SQL statement in the OceanBase client (OBClient) to view the result.
obclient [test]> SELECT * FROM test_tbl1;The following result is returned:
+------+--------------+ | id | name | +------+--------------+ | 5 | test_update | | 6 | test_insert6 | | 7 | test_insert7 | | 8 | test_insert8 | | 9 | test_insert9 | +------+--------------+ 5 rows in set
Project code overview
Click dbcp-mysql-client to download the project code, which is a compressed package named dbcp-mysql-client.zip.
After you decompress the file, a folder named dbcp-mysql-client is created. The directory structure is as follows:
dbcp-mysql-client
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── Main.java
│ └── resources
│ └── db.properties
└── pom.xml
File description:
src: The source code root directory.main: The main code directory, which contains the primary 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 sample file. It contains the logic for creating tables and for 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 the relevant parameters for the database connection.pom.xml: The configuration file for the Maven project. It is used to manage the project's dependencies and build settings.
pom.xml code overview
The pom.xml file is the configuration file for a Maven project. It defines the project's dependencies, plugins, and build rules. Maven is a Java project management tool that automatically downloads dependencies, and compiles and packages projects.
The code in this topic's pom.xml file includes the following main parts:
File declaration statement.
This declares that the file is an XML file, the XML version is
1.0, and the character encoding isUTF-8.Code:
<?xml version="1.0" encoding="UTF-8"?>Configure the POM namespace and POM model version.
The
xmlnsattribute specifies the POM namespace ashttp://maven.apache.org/POM/4.0.0.The
xmlns:xsiattribute specifies the XML namespace ashttp://www.w3.org/2001/XMLSchema-instance.The
xsi:schemaLocationattribute specifies the POM namespace ashttp://maven.apache.org/POM/4.0.0and the location of the POM XSD file ashttp://maven.apache.org/xsd/maven-4.0.0.xsd.The
<modelVersion>element specifies that the POM model version used by this POM file is4.0.0.
Code:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- Other configurations --> </project>Configure basic information.
The
<groupId>element specifies the project's organization ascom.example.The
<artifactId>element specifies the project's name asdbcp-mysql-client.The
<version>element specifies the project's version number as1.0-SNAPSHOT.
Code:
<groupId>com.example</groupId> <artifactId>dbcp-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>Configure project source file properties.
This configures the
maven-compiler-pluginto use Java 8 for both the source code and the compiled bytecode. This ensures that the project is compiled and runs correctly in a Java 8 environment.NoteJava 1.8 and Java 8 are different names for the same version.
Code:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build>Configure project dependencies.
Define dependencies using the
<dependency>element:MySQL JDBC dependency:
The
<groupId>element specifies the dependency's organization asmysql.The
<artifactId>element specifies the dependency's name asmysql-connector-java.The
<version>element specifies the dependency's version number as5.1.47.
dbcp dependency:
The
<groupId>element specifies the dependency's organization asorg.apache.commons.The
<artifactId>element specifies the dependency's name ascommons-dbcp2.The
<version>element specifies the dependency's version number as2.9.0.
Code:
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.9.0</version> </dependency> </dependencies>
db.properties code overview
db.properties is the connection pool configuration file for the sample in this topic. It contains the configuration properties for the connection pool. These properties include the driver's class name, database URL, username, password, connection pool size and limits, connection timeout, and options for handling abandoned connections.
The code in this topic's db.properties file includes the following main parts:
Configure database connection parameters.
Set the driver's class name to the MySQL JDBC driver class name,
com.mysql.jdbc.Driver.Set the database connection URL, which includes the host IP, port number, and the database to access.
Set the database username.
Set the database password.
Set the connection properties.
useSSL=falseindicates that the connection does not use SSL encryption.characterEncoding=UTF-8indicates that UTF-8 encoding is used for data transmission.
Code:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://$host:$port/$database_name username=$user_name password=$password connectionProperties=useSSL=false;characterEncoding=UTF-8Parameter 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 tenant's connection account.$password: The account password.
Configure other DBCP connection pool parameters.
Set the initial size of the connection pool to
30. This is the number of connections to create when the pool starts.Set the maximum number of connections in the pool to
30. This is the maximum number of connections allowed in the pool.Set the maximum number of idle connections allowed in the pool to
10.Set the minimum number of idle connections to maintain in the pool to
5. If the number of idle connections falls below this value, the pool creates new connections.Set the maximum wait time to obtain a connection from the pool to
1000milliseconds. If all connections in the pool are in use, the operation to obtain a connection waits until a connection becomes available or the maximum wait time is exceeded.Set the timeout before an abandoned connection is removed to
1second.NoteThe default value for
removeAbandonedTimeoutis 300 seconds. In this sample, it is set to 1 second for testing purposes. Adjust this value as needed to meet your application's requirements.Specifies whether the connection pool revokes idle connections in the program:
Set whether to detect and remove abandoned connections during maintenance. Set to
true.Set whether to detect and remove abandoned connections when borrowing a connection from the pool. Set to
true.
Code:
initialSize=30 maxTotal=30 maxIdle=10 minIdle=5 maxWaitMillis=1000 removeAbandonedTimeout=1 removeAbandonedOnMaintenance=true removeAbandonedOnBorrow=true
The specific property (parameter) configuration depends on your project requirements and database characteristics. Adjust the configuration as needed. For more information about DBCP connection pool parameters, see BasicDataSource Configuration Parameters.
DBCP connection pool basic data source configuration parameters:
Category |
Property |
Default value |
Description |
Required parameters |
driverClass |
N/A |
Specifies the class name of the database driver. |
url |
N/A |
Specifies the URL to use when connecting to the database. |
|
username |
N/A |
Specifies the username to use when connecting to the database. |
|
password |
N/A |
Specifies the password to use when connecting to the database. |
|
Recommended parameters |
initialSize |
0 |
Specifies the initial size of the connection pool, which is the number of initial connections created when the pool starts. If you set this to a value greater than 0, the specified number of connections are created during pool initialization. This can pre-create connections and reduce latency for the client's first connection request. |
maxTotal |
8 |
Specifies the maximum number of connections in the connection pool. If you set this to a negative number, there is no limit. |
|
maxIdle |
8 |
Specifies the maximum number of idle connections allowed in the pool without releasing extra connections. If you set this to a negative number, there is no limit. |
|
minIdle |
0 |
Specifies the minimum number of idle connections to maintain in the pool without releasing extra connections. If you set this to a negative number, there is no limit. |
|
maxWaitMillis |
indefinitely |
Specifies the maximum wait time (in milliseconds) to get a connection from the pool. If set to -1, it means wait indefinitely. If set to a positive number, when all connections in the pool are in use, the operation to get a connection waits for the specified time. An exception is thrown if the time is exceeded. |
|
validationQuery |
N/A |
Specifies the SQL query statement used to validate whether a connection is valid. If specified, this query must be an |
|
testOnBorrow |
true |
Specifies whether to validate an object when it is borrowed from the pool. If the object fails validation, it is dropped from the pool, and another object will be borrowed. |
|
testWhileIdle |
false |
Specifies whether the connection pool validates connections when they are idle. If set to |
|
Optional parameters |
connectionProperties |
N/A |
Specifies additional connection properties in key-value pairs. These properties are passed to the underlying JDBC driver when a database connection is obtained. The string format must be
Important
The |
|
false |
These two parameters control the removal behavior for connections that are considered abandoned.
By setting the above two parameters to |
Main.java code overview
The Main.java file is part of the sample program. It demonstrates how to obtain a database connection from a DBCP connection pool, perform a series of database operations, such as creating a table, inserting, deleting, updating, and querying data, and then printing the query results.
The code in this topic's Main.java file includes the following main parts:
Import required classes and interfaces.
This section imports the required classes and interfaces for reading files, database operations, and the database connection pool.
Declares the
com.examplepackage, which contains the current Java class.Imports the
java.io.FileInputStreamclass to read files.Imports the
java.sql.Connectioninterface, which represents a database connection.Imports the
java.sql.PreparedStatementinterface, which represents a precompiled SQL statement.Imports the
java.sql.ResultSetinterface, which represents the result set of a database query.Imports the
java.sql.SQLExceptionexception class, which represents an SQL operation exception.Imports the
java.util.Propertiesclass to load configuration files.Imports the
org.apache.commons.dbcp2.BasicDataSourceclass, which represents the database connection pool.Imports the
org.apache.commons.dbcp2.BasicDataSourceFactoryclass to create the database connection pool.
Code:
package com.example; import java.io.FileInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.dbcp2.BasicDataSourceFactory;Define the class name and methods.
Create the Main class and define a
mainmethod as the program's entry point.In the
mainmethod, first call thecreateDataSource()method to create thedataSourceconnection pool object.Use a
try-with-resourcesstatement to ensure that the connection pool object is automatically closed.In the
tryblock, call thegetConnection()method to obtain aconndatabase connection object from the connection pool.Sequentially call the
createTable(),insertData(),deleteData(),updateData(), andqueryData()methods to perform the corresponding database operations.If an exception occurs, print the exception information in the
catchblock.
Code:
public class Main { public static void main(String[] args) { try (BasicDataSource dataSource = createDataSource()) { try (Connection conn = dataSource.getConnection()) { createTable(conn); insertData(conn); deleteData(conn); updateData(conn); queryData(conn); } } catch (Exception e) { e.printStackTrace(); } } // Create a connection pool // Define a method to create a table // Define a method to insert data // Define a method to delete data // Define a method to update data // Define a method to query data }Create a connection pool.
This method creates a database connection pool by reading parameters from a configuration file to initialize the pool object. The steps are as follows:
Define a private static method
createDataSource()with a return type ofBasicDataSource. The method may throw anException.Create a
Propertiesobject namedpropsto store the database connection configuration information.Create a
FileInputStreamobject namedisto read thedb.propertiesfile located in thesrc/main/resourcesdirectory.Use the
load()method to load the key-value pairs from thedb.propertiesfile into the props object.Call the
BasicDataSourceFactory.createDataSource(props)method, using thepropsobject as a parameter to create and return aBasicDataSourceobject.
Code:
private static BasicDataSource createDataSource() throws Exception { Properties props = new Properties(); FileInputStream is = new FileInputStream("src/main/resources/db.properties"); props.load(is); return BasicDataSourceFactory.createDataSource(props); }Define a method to create a table.
This method creates a specified table in the database. It accepts a connection object as a parameter and uses a precompiled statement to execute the SQL statement for creating the table. The steps are as follows:
Define a private static method
createTable()that accepts aConnectionobject as a parameter. The method may throw anSQLException.Define a string variable
createTableSqlto store the SQL statement for creating the table. The SQL statement specifies the table name astest_tbl1and defines two columns: anINTtype column namedidand aVARCHAR(32)type column namedname.Use the
conn.prepareStatement(createTableSql)method to create aPreparedStatementobject namedcreateTableStmt. This object is used to execute the precompiled SQL statement.Call the
execute()method to execute the SQL statement to create the table.
Code:
private static void createTable(Connection conn) throws SQLException { String createTableSql = "CREATE TABLE test_tbl1 (id INT, name VARCHAR(32))"; try (PreparedStatement createTableStmt = conn.prepareStatement(createTableSql)) { createTableStmt.execute(); } }Define a method to insert data.
This method inserts specified data into a database table. It accepts a connection object as a parameter and uses a precompiled statement to execute the SQL statement for inserting data. The steps are as follows:
Define a private static method
insertData()that accepts aConnectionobject as a parameter. The method may throw anSQLException.Define a string variable
insertDataSqlto store the SQL statement for inserting data.Use the
conn.prepareStatement(insertDataSql)method to create aPreparedStatementobject namedinsertDataStmt. This object is used to execute the precompiled SQL statement.Use a
forloop to insert data into the table:The loop iterates
10times to insert 10 records.Set the first parameter in the SQL statement to the value of the loop variable
i.Set the second parameter to the string
test_insert + i.You can insert data into the database by calling the
executeUpdate()method to execute an SQL statement.
Code:
private static void insertData(Connection conn) throws SQLException { String insertDataSql = "INSERT INTO test_tbl1 (id, name) VALUES (?, ?)"; try (PreparedStatement insertDataStmt = conn.prepareStatement(insertDataSql)) { for (int i = 0; i < 10; i++) { insertDataStmt.setInt(1, i); insertDataStmt.setString(2, "test_insert" + i); insertDataStmt.executeUpdate(); } } }Define a method to delete data.
This method deletes data that meets specific conditions from the database. It accepts a connection object as a parameter and uses a precompiled statement to execute the SQL statement for deleting data. The steps are as follows:
Define a private static method
deleteData()that accepts aConnectionobject as a parameter. The method may throw anSQLException.Define a string variable
deleteDataSqlto store the SQL statement for deleting data.Use the
conn.prepareStatement(deleteDataSql)method to create aPreparedStatementobject nameddeleteDataStmt. This object is used to execute the precompiled SQL statement.Use
setInt()to set the parameter value to 5 in the SQL statement.You can call
executeUpdate(). This method executes an SQL statement to delete data that meets specific conditions from the database.
Code:
private static void deleteData(Connection conn) throws SQLException { String deleteDataSql = "DELETE FROM test_tbl1 WHERE id < ?"; try (PreparedStatement deleteDataStmt = conn.prepareStatement(deleteDataSql)) { deleteDataStmt.setInt(1, 5); deleteDataStmt.executeUpdate(); } }Define a method to update data.
This method updates data that meets specific conditions in the database. It accepts a connection object as a parameter and uses a precompiled statement to execute the SQL statement for updating data. The steps are as follows:
Define a private static method
updateData()that accepts aConnectionobject as a parameter. The method may throw anSQLException.Define a string variable
updateDataSqlto store the SQL statement for updating data.Use the
conn.prepareStatement(updateDataSql)method to create aPreparedStatementobject namedupdateDataStmt. This object is used to execute the precompiled SQL statement.Set the first parameter in the SQL statement to the string
test_update.Set the second parameter to
5.Call the
executeUpdate()method to execute an SQL statement that updates data meeting the specified conditions in the database.
Code:
private static void updateData(Connection conn) throws SQLException { String updateDataSql = "UPDATE test_tbl1 SET name = ? WHERE id = ?"; try (PreparedStatement updateDataStmt = conn.prepareStatement(updateDataSql)) { updateDataStmt.setString(1, "test_update"); updateDataStmt.setInt(2, 5); updateDataStmt.executeUpdate(); } }Define a method to query data.
This method queries and processes data from the database. It accepts a connection object as a parameter and uses a precompiled statement to execute the SQL statement for querying data. The steps are as follows:
Define a private static method
queryData()that accepts aConnectionobject as a parameter. The method may throw anSQLException.Define a string variable
queryDataSqlto store the SQL statement for querying data.Use the
conn.prepareStatement(queryDataSql)method to create aPreparedStatementobject namedqueryDataStmt. This object is used to execute the precompiled SQL statement.Execute the SQL query and use a
ResultSetobject namedrsto store the result.Use a
whileloop and thers.next()method to traverse the query result set:You can use the
getInt()method to retrieve the integer value from theidcolumn in the result set and assign the value to theidvariable.Use the
getString()method to retrieve the string value from thenamecolumn of the result set, and assign it to thenamevariable.Print the
idandnamevalues.
Code:
private static void queryData(Connection conn) throws SQLException { String queryDataSql = "SELECT * FROM test_tbl1"; try (PreparedStatement queryDataStmt = conn.prepareStatement(queryDataSql)) { try (ResultSet rs = queryDataStmt.executeQuery()) { while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("id: " + id + ", name: " + name); } } } }
Complete code sample
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.example</groupId>
<artifactId>dbcp-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.47</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
db.properties
jdbcUrl=jdbc:mysql://$host:$port/$database_name?useSSL=false
username=$user_name
password=$password
dataSource.cachePrepStmts=true
dataSource.prepStmtCacheSize=250
dataSource.maxLifetime=1800000
dataSource.idleTimeout=600000
dataSource.connectionTimeout=30000
Main.java
package com.example;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class Main {
public static void main(String[] args) {
try {
HikariConfig config = new HikariConfig("/db.properties");
try (HikariDataSource dataSource = new HikariDataSource(config);
Connection conn = dataSource.getConnection()) {
createTable(conn);
insertData(conn, 1, "A1");
insertData(conn, 2, "A2");
selectData(conn);
updateData(conn, "test_update", 1);
selectData(conn);
deleteData(conn, 2);
selectData(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void createTable(Connection conn) throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS test_hikaricp (id INT, name VARCHAR(50))";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.executeUpdate();
System.out.println("Table created successfully.");
}
}
private static void insertData(Connection conn, int id, String name) throws SQLException {
String sql = "INSERT INTO test_hikaricp (id, name) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.setString(2, name);
pstmt.executeUpdate();
System.out.println("Data inserted successfully.");
}
}
private static void selectData(Connection conn) throws SQLException {
String sql = "SELECT * FROM test_hikaricp";
try (PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
System.out.println("User Data:");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
System.out.println();
}
}
private static void updateData(Connection conn, String name, int id) throws SQLException {
String sql = "UPDATE test_hikaricp SET name = ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setInt(2, id);
pstmt.executeUpdate();
System.out.println("Data updated successfully.");
}
}
private static void deleteData(Connection conn, int id) throws SQLException {
String sql = "DELETE FROM test_hikaricp WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.executeUpdate();
System.out.println("Data deleted successfully.");
}
}
}
References
For more information about MySQL Connector/J, see Overview of MySQL Connector/J.