This topic describes how to use the C3P0 connection pool, OceanBase Connector/J, and OceanBase Cloud to build an application that performs basic database operations, including table creation, data insertion, data deletion, data updating, and data query.
Download the c3p0-oceanbase-jdbc sample project Prerequisites
You have registered an account for OceanBase Cloud and created an instance and an OceanBase Cloud Oracle-compatible tenant. For more information, see Create an instance and Create a tenant.
You have obtained the connection string of the target Oracle-compatible tenant. For more information, see Obtain the connection string.
You have installed JDK 1.8 and Maven.
You have installed Eclipse.
Note
The code in this topic is run in Eclipse IDE for Java Developers 2022-03. You can also use any other tool that you prefer to run the sample code.
Procedure
Note
The following steps describe how to compile and run the c3p0-oceanbase-jdbc project in Eclipse IDE for Java Developers 2022-03 on Windows. If you are using a different operating system or compiler, the steps may vary slightly.
Step 1: Import the c3p0-oceanbase-jdbc project into Eclipse
Open Eclipse and select File > Open Projects from File System.
In the dialog box that appears, click Directory to select the project directory, then click Finish to complete the import.
Note
When importing a Maven project into Eclipse, it automatically detects the
pom.xmlfile in the project, downloads the required dependency libraries based on the described dependencies in the file, and adds them to the project.
View the project.

Step 2: Modify the database connection information in the c3p0-oceanbase-jdbc project
Modify the database connection information in the c3p0-oceanbase-jdbc/src/main/resources/c3p0-config.xml file based on the connection string obtained in the prerequisites.
Here is an example:
...
<property name="jdbcUrl">jdbc:oceanbase://t5******.********.oceanbase.cloud:1521/test?useSSL=false&useUnicode=true&characterEncoding=utf8</property>
<property name="user">test_user</property>
<property name="password">******</property>
...
- The connection address is
t5******.********.oceanbase.cloud. - The access port is 1521.
- The database name to be accessed is
test. - The tenant connection account is
test_user. - The password is
******.
Step 3: Run the c3p0-oceanbase-jdbc project
In the Project Explorer view, locate and expand the src/main/java directory.
Right-click the Main.java file and select Run As > Java Application.

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

You can also execute the following SQL statement in OceanBase Client (OBClient) to view the results.
obclient [SYS]> SELECT * FROM test_schema001.test_c3p0;The returned result is as follows:
+------+--------------+ | ID | NAME | +------+--------------+ | 5 | test_update | | 6 | test_insert6 | | 7 | test_insert7 | | 8 | test_insert8 | | 9 | test_insert9 | +------+--------------+ 5 rows in set
Project code
Click c3p0-oceanbase-jdbc to download the project code, which is a compressed file named c3p0-oceanbase-jdbc.zip.
After decompressing the file, you will find a folder named c3p0-oceanbase-jdbc. The directory structure is as follows:
c3p0-oceanbase-jdbc
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── Main.java
│ └── resources
│ └── c3p0-config.xml
└── 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 of the sample project.Main.java: the main class, containing logic for creating tables and inserting data.resources: the directory for resource files, including configuration files.c3p0-config.xml: the configuration file for the C3P0 connection pool.pom.xml: the configuration file for the Maven project, used to manage project dependencies and build settings.
Introduction to the pom.xml file
The pom.xml file is a configuration file for Maven projects, defining 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 article mainly includes the following parts:
File declaration statement.
This statement declares the file as an XML file using XML version
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure the namespace and POM model version.
- Use
xmlnsto specify the POM namespace ashttp://maven.apache.org/POM/4.0.0. - Use
xmlns:xsito specify the XML namespace ashttp://www.w3.org/2001/XMLSchema-instance. - Use
xsi:schemaLocationto specify 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. - Use
<modelVersion>to specify the POM model version used by the POM file as4.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>- Use
Configure basic information.
- Use
<groupId>to specify the project's organization ascom.example. - Use
<artifactId>to specify the project name astestc3p0. - Use
<version>to specify the project version as1.0-SNAPSHOT.
Sample code:
<groupId>com.example</groupId> <artifactId>testc3p0</artifactId> <version>1.0-SNAPSHOT</version>- Use
Configure the properties of the project's source files.
Specify the Maven compiler plugin as
maven-compiler-pluginand set 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 setup 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.
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>Configure the components that the project depends on.
Note
This section defines the project's dependency on OceanBase Connector/J V2.4.2. For information about other versions, see OceanBase JDBC driver
Use
<dependency>to define dependencies:oceanbase-client dependency:
- Use
<groupId>to specify the dependency's organization ascom.oceanbase. - Use
<artifactId>to specify the dependency name asoceanbase-client. - Use
<version>to specify the dependency version as2.4.2.
- Use
C3P0 dependency:
- Use
<groupId>to specify the dependency's organization ascom.mchange. - Use
<artifactId>to specify the dependency name asc3p0. - Use
<version>to specify the dependency version as0.9.5.5.
- Use
Sample code:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> </dependencies>
Introduction to c3p0-config.xml
The c3p0-config.xml file is a C3P0 connection pool configuration file used to configure properties related to database connections. By setting the values of various <property> elements, you can configure properties such as the database driver, connection URL, username, password, and connection pool size.
The code in the c3p0-config.xml file in this topic mainly includes the following parts:
A file declaration statement.
This statement declares the file to be an XML file that uses XML version
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Basic configuration.
- The
<c3p0-config>element is used to include the configuration information of the c3p0 connection pool. - The
<named-config name="oceanbase">element defines a named configuration namedoceanbase. In the code, you can use this name to reference the named configuration and obtain connection information and connection pool properties related to theoceanbasedatabase.
Sample code:
<c3p0-config> <named-config name="oceanbase"> // Configure the values of various <property> elements </named-config> </c3p0-config>- The
Database driver configuration.
The
<property>element is used to specify the class name of the JDBC driver for connecting to the OceanBase database ascom.oceanbase.jdbc.Driver.Sample code:
<property name="driverClass">com.oceanbase.jdbc.Driver</property>Database connection information configuration.
- The database connection URL is set, including the connection address, port number, schema to be accessed, and URL parameters.
- The database username is configured.
- The database password is configured.
Sample code:
<property name="jdbcUrl">jdbc:oceanbase://$host:$port/$schema_name?useSSL=false&useUnicode=true&characterEncoding=utf8</property> <property name="user">$user_name</property> <property name="password">$password</property>Parameter description:
$host: The value of the-hparameter in the connection string, which specifies the connection address of the OceanBase Cloud database.$port: The value of the-Pparameter in the connection string, which specifies the connection port of the OceanBase Cloud database.$schema_name: The value of the-Dparameter in the connection string, which specifies the name of the database to be accessed.Other parameters are as follows:
useSSL=false: Disables SSL encryption, indicating that secure socket layer is not used to protect data transmission.seUnicode=true: Enables Unicode character encoding to ensure that various character sets can be processed correctly.characterEncoding=utf8: Specifies the use of UTF-8 character encoding.&: An XML entity reference used to represent the&character. In XML,&is a special character that must be represented by an entity reference to avoid conflicts with XML syntax.
For more information about URL parameters, see Database URL.
$user_name: The value of the-uparameter in the connection string, which specifies the account name.$password: The value of the-pparameter in the connection string, which specifies the account password.
Other c3p0 connection pool configuration items.
- The number of connections to be added at a time when the connection pool needs more connections is set to 20. That is, when the number of connections in the connection pool is insufficient, 20 connections are added each time.
- The initial size of the connection pool is set to 10. That is, 10 connections are pre-created when the connection pool is started.
- The minimum number of connections in the connection pool is set to 5. That is, the number of connections kept in the connection pool is not less than 5.
- The maximum number of connections in the connection pool is set to 30. That is, the number of connections allowed in the connection pool does not exceed 30.
- The maximum number of cached statements per connection is set to 0. That is, no statements are cached.
- The maximum number of cached statements per connection in the connection pool is set to 0. That is, no statements are cached per connection.
- The number of auxiliary threads used by c3p0 is set to 3. These auxiliary threads are used to execute slow JDBC operations.
- The attribute check cycle for c3p0 connections is set to 3 seconds. That is, the attributes of connections are checked every 3 seconds.
- The timeout period for obtaining a connection is set to 1000 milliseconds. That is, if a connection cannot be obtained within 1000 milliseconds, a timeout exception is thrown.
- The idle connection check cycle in the connection pool is set to 3 seconds. That is, the status of idle connections is checked every 3 seconds.
- The maximum idle time of a connection in the connection pool is set to 10 seconds. That is, if a connection is not used for 10 seconds, it will be closed.
- The maximum idle time of a connection exceeding the maximum number of connections in the connection pool is set to 5 seconds. That is, if a connection exceeds the maximum number of connections and is idle for more than 5 seconds, it will be closed.
- The retry delay when attempting to obtain a connection is set to 1000 milliseconds. That is, if obtaining a connection fails, it will be retried after 1000 milliseconds.
- The automatic test table for c3p0 is set to "test". This is a special table used to test whether a connection is valid.
- Whether to test the validity of a connection when returning it to the connection pool is set. If set to true, the validity of a connection is tested when it is returned to the connection pool.
Sample code:
<property name="acquireIncrement">20</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">30</property> <property name="maxStatements">0</property> <property name="maxStatementsPerConnection">0</property> <property name="numHelperThreads">3</property> <property name="propertyCycle">3</property> <property name="checkoutTimeout">1000</property> <property name="idleConnectionTestPeriod">3</property> <property name="maxIdleTime">10</property> <property name="maxIdleTimeExcessConnections">5</property> <property name="acquireRetryDelay">1000</property> <property name="automaticTestTable">test</property> <property name="testConnectionOnCheckin">true</property>
Notice
The specific property (parameter) configuration depends on the project requirements and database characteristics. We recommend that you adjust and configure the parameters based on your actual situation. For more information about C3P0 connection pool parameters, see C3P0.
Common basic configuration items of the C3P0 connection pool:
| Category | Attribute | Default value | Description |
|---|---|---|---|
| Required | driverClass | N/A | The name of the driver class. |
| jdbcUrl | N/A | The URL of the database to connect to. | |
| user | N/A | The username to use when connecting to the database. | |
| password | N/A | The password to use when connecting to the database. | |
| Basic | acquireIncrement | 3 | The number of connections to acquire at once when the connection pool needs connections. For example, if acquireIncrement is set to 20 and there are only 5 idle connections in the connection pool, the pool will create 20 new connections to meet the application's needs when connections are requested. |
| acquireRetryAttempts | 30 | The number of retries to attempt when acquiring a connection from the connection pool. If this value is less than or equal to zero, C3P0 will continue to attempt to acquire a connection indefinitely. | |
| maxIdleTime | 0 | The maximum idle time for a connection in the connection pool, in seconds. A value of 0 means that idle connections will never expire. For example, if maxIdleTime is set to 10 seconds, any idle connection in the pool that is not used for more than 10 seconds will be closed and removed from the pool. The next time the application requests a connection, the pool will create a new one. |
|
| maxPoolSize | 15 | The maximum number of connections in the connection pool. When the number of connections in the pool reaches the value specified by maxPoolSize, new connection requests will be blocked until a connection is released back to the pool. |
|
| MinPoolSize | 3 | The minimum number of connections in the connection pool. The pool will maintain at least the number of connections specified by minPoolSize even when connections are not in use. |
|
| initialPoolSize | 3 | The number of connections to pre-create when the connection pool starts. This value should be between minPoolSize and maxPoolSize. That is, when the pool is initialized, it will create the number of connections specified by initialPoolSize. |
|
| Optional | acquireRetryDelay | 1000 | The retry delay time in milliseconds when acquiring a connection. When an application requests a connection from the pool and no available connections are found, the pool may fail to acquire a connection. In this case, the pool will retry based on the configuration of acquireRetryDelay. |
| autoCommitOnClose | false | Whether to automatically commit transactions when the connection is closed. The default value is false, meaning that transactions will not be automatically committed when the connection is closed. If the application needs to explicitly commit transactions before closing the connection, set autoCommitOnClose to true.
NoticeAutomatic transaction commit may lead to data inconsistency or loss. Therefore, |
|
| automaticTestTable | null | The name of the automatic test table for the connection pool. C3P0 will create an empty table with the specified name and use queries on this table to test the connection. The default value is null, indicating that no test statements will be executed. For example, if automaticTestTable is set to test, C3P0 will create an empty table named test and use its built-in query statements for testing.
NoteIf both |
|
| idleConnectionTestPeriod | 0 | The interval in milliseconds for idle connection detection in the connection pool. That is, the pool will periodically test idle connections at the specified intervals. The default value is 0, indicating that no idle connection detection will be performed. | |
| maxStatements | 0 | The maximum number of prepared statements in the connection pool.
Note
|
|
| maxStatementsPerConnection | 0 | Specifies the maximum number of prepared statements allowed per connection.
Note
|
|
| numHelperThreads | 3 | Specifies the number of helper threads used for asynchronous task processing.
Note
|
|
| preferredTestQuery | null | Specifies the test statement executed for all connection tests. Using connection testing can significantly improve the test speed.
NoticeThe test table must exist when the data source is initialized. |
|
| checkoutTimeout | 0 | Specifies the timeout for obtaining a connection from the connection pool, in milliseconds. The default value of 0 indicates no timeout. When the connection pool is exhausted, the client calls getConnection() and waits for a new connection. If the timeout is reached, a SQLException is thrown. |
|
| Not recommended | breakAfterAcquireFailure | false | Controls whether to interrupt the connection pool's acquisition operation when a connection acquisition fails. If a connection acquisition fails, all threads waiting for a connection from the connection pool will throw an exception. However, the data source remains valid and will continue to attempt to acquire a connection on the next call to getConnection().
|
| testConnectionOnCheckout | false | Specifies whether to test the connection when obtaining it from the connection pool.
NoteWhile executing a connection test ensures the connection is valid, it also incurs additional overhead. Therefore, whether to enable connection testing should be decided based on specific application requirements and performance needs. If the application has high availability requirements for connections, connection testing can be enabled. However, if connections are frequently acquired and released from the connection pool, it may lead to excessive connection testing, which can impact performance. |
|
| testConnectionOnCheckin | false | Specifies whether to test the connection when returning it to the connection pool.
NoteWhile executing a connection test ensures the connection is valid, it also incurs additional overhead. Therefore, whether to enable connection testing should be decided based on specific application requirements and performance needs. If the application has high availability requirements for connections, connection testing can be enabled. However, if connections are frequently acquired and released from the connection pool, it may lead to excessive connection testing, which can impact performance. |
Main.java code introduction
The Main.java file is part of the sample program, demonstrating how to obtain a database connection using the c3p0 connection pool, and perform a series of database operations within a transaction, including creating a table, inserting data, deleting data, updating data, querying data, and printing the query results. It shows how to use the c3p0 connection pool to manage database connections and execute transaction operations to improve the efficiency and performance of database operations.
The code in the Main.java file in this topic mainly includes the following parts:
Define the package and import the
java.sqlinterface.- Declare the package name of the current code as
com.example. - Import the
java.sql.Connectionclass, which is used to represent a database connection. - Import the
java.sql.PreparedStatementclass, which is used to execute precompiled database operations. - Import the
java.sql.ResultSetclass, which is used to represent a database query result set. - Import the
com.mchange.v2.c3p0.ComboPooledDataSourceclass, which is used to use the c3p0 connection pool.
Code:
package com.example; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.mchange.v2.c3p0.ComboPooledDataSource;- Declare the package name of the current code as
Define the class name and method.
- Define a public class named
Mainas the entry point of the program. The class name must be consistent with the file name. - Define a public static method
mainas the starting point of the program. - Use the
try-with-resourcesstatement to obtain a database connection and create a precompiled SQL statement. - Perform database transaction operations.
- Capture any exceptions that may occur and print the exception stack information.
- Define a private static method
getConnectionto obtain a database connection from the c3p0 connection pool. Inside the method, first create aComboPooledDataSourceobjectcpdsthat specifies the connection pool configuration through the parameteroceanbase. Then, obtain a database connection from the connection pool using thecpds.getConnection()method and return it.
Code:
public class Main { public static void main(String[] args) { try ( // Obtain a database connection // Create a precompiled SQL statement ) { // Database transaction operations: start transaction, create table, insert data, delete data, update data, query data, and commit transaction } catch (Exception e) { e.printStackTrace(); } } private static Connection getConnection() throws Exception { ComboPooledDataSource cpds = new ComboPooledDataSource("oceanbase"); return cpds.getConnection(); } }- Define a public class named
Obtain a database connection.
Obtain a database connection and assign it to the
connvariable.Code:
Connection conn = getConnection();Create a precompiled SQL statement.
- Create a precompiled SQL statement for creating a database table named
test_c3p0. - Create a precompiled SQL statement for inserting data into the
test_c3p0table. - Create a precompiled SQL statement for deleting data from the
test_c3p0table. - Create a precompiled SQL statement for updating data in the
test_c3p0table. - Create a precompiled SQL statement for querying data from the
test_c3p0table.
Code:
PreparedStatement stmtCreate = conn.prepareStatement("CREATE TABLE test_c3p0 (id NUMBER, name VARCHAR2(32))"); PreparedStatement stmtInsert = conn.prepareStatement("INSERT INTO test_c3p0 VALUES (?, ?)"); PreparedStatement stmtDelete = conn.prepareStatement("DELETE FROM test_c3p0 WHERE id < ?"); PreparedStatement stmtUpdate = conn.prepareStatement("UPDATE test_c3p0 SET name = ? WHERE id = ?"); PreparedStatement stmtSelect = conn.prepareStatement("SELECT * FROM test_c3p0")- Create a precompiled SQL statement for creating a database table named
Start a transaction.
Set the auto-commit mode of the database connection to
falseto enable the transaction mechanism.Code:
conn.setAutoCommit(false);Create a table.
Execute the SQL statement for creating a table.
Code:
stmtCreate.execute();Insert data.
Use a
forloop to insert 10 rows of data into thetest_c3p0table. The value of the first column is the value of the variablei, and the value of the second column is the stringtest_insertconcatenated with the value of the variablei.Code:
for (int i = 0; i < 10; i++) { stmtInsert.setInt(1, i); stmtInsert.setString(2, "test_insert" + i); stmtInsert.executeUpdate(); }Delete data.
Set the parameter of the delete statement to 5 and execute the delete operation.
Code:
stmtDelete.setInt(1, 5); stmtDelete.executeUpdate();Update data.
Set the first parameter of the update statement to
test_updateand the second parameter to 5, and execute the update operation.Code:
stmtUpdate.setString(1, "test_update"); stmtUpdate.setInt(2, 5); stmtUpdate.executeUpdate();Query data.
- Execute the query statement and save the query results in the
ResultSetobjectrs. - Use a while loop to check if there are more rows of data in the result set by calling
rs.next(). If there are, execute the code inside the loop. - The code inside the loop prints the values of the
idandnamecolumns for each row. - Close the result set and release the related resources.
Code:
ResultSet rs = stmtSelect.executeQuery(); while (rs.next()) { System.out.println(rs.getInt("id") + " " + rs.getString("name")); } rs.close();- Execute the query statement and save the query results in the
Commit the transaction.
Code:
conn.commit();
Complete code
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>testc3p0</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>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="oceanbase">
<!-- Configure Database Driver -->
<property name="driverClass">com.oceanbase.jdbc.Driver</property>
<!-- Configure Database Link Address -->
<property name="jdbcUrl">jdbc:oceanbase://$host:$port/$schema_name?useSSL=false&useUnicode=true&characterEncoding=utf8</property>
<!-- Configure database username -->
<property name="user">$user_name</property>
<!-- Configure database password -->
<property name="password">$password</property>
<!-- How many connection objects does the database Connection pool want from the database at one time -->
<property name="acquireIncrement">20</property>
<!-- Initialize connections -->
<property name="initialPoolSize">10</property>
<!-- Minimum number of connections -->
<property name="minPoolSize">5</property>
<!-- The maximum number of connections reserved in the Connection pool. Default: 15 -->
<property name="maxPoolSize">30</property>
<!-- JDBC standard parameter used to control the number of PreparedStatements loaded within the data source. However, the pre cached statements belong to a single connection rather than the entire Connection pool. So setting this parameter requires considering multiple factors. If both maxStatements and maxStatementsPerConnection are 0, the cache is turned off. Default:0 -->
<property name="maxStatements">0</property>
<!-- MaxStatementsPerConnection defines the maximum number of cached statements owned by a single connection in the Connection pool. Default: 0 -->
<property name="maxStatementsPerConnection">0</property>
<!-- C3p0 is an asynchronous operation, and slow JDBC operations are completed by the helper process. Expanding these operations can effectively improve performance by enabling multiple operations to be executed simultaneously through multithreading. Default:3 -->
<property name="numHelperThreads">3</property>
<!-- The user can wait up to 300 seconds before modifying the system configuration parameters. Default: 300 -->
<property name="propertyCycle">3</property>
<!-- The default setting for obtaining the connection timeout is to wait for a unit of milliseconds -->
<property name="checkoutTimeout">1000</property>
<!-- Check all free connections in the Connection pool every few seconds. Default: 0 -->
<property name="idleConnectionTestPeriod">3</property>
<!-- The maximum idle time, within seconds, if not used, the connection will be discarded. If it is 0, it will never be discarded. Default: 0 -->
<property name="maxIdleTime">10</property>
<!-- Configure the lifetime of the connection. Connections beyond this time will be automatically disconnected and discarded by the Connection pool. Of course, the connection being used will not be immediately disconnected, but will wait for it to close before disconnecting. When configured to 0, there is no restriction on the lifetime of the connection. -->
<property name="maxIdleTimeExcessConnections">5</property>
<!-- The interval time between two connections, in milliseconds. Default: 1000 -->
<property name="acquireRetryDelay">1000</property>
<!-- C3p0 will create an empty table called Test and use its built-in query statement for testing. If this parameter is defined, the property preferredTestQuery will be ignored. You cannot perform any operations on this Test table, it will only be used for c3p0 testing. Default: null -->
<property name="automaticTestTable">test</property>
<!-- Test if the connection is valid when obtaining it -->
<property name="testConnectionOnCheckin">true</property>
</named-config>
</c3p0-config>
package com.example;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class Main {
public static void main(String[] args) {
try (Connection conn = getConnection();
PreparedStatement stmtCreate = conn.prepareStatement("CREATE TABLE test_c3p0 (id NUMBER, name VARCHAR2(32))");
PreparedStatement stmtInsert = conn.prepareStatement("INSERT INTO test_c3p0 VALUES (?, ?)");
PreparedStatement stmtDelete = conn.prepareStatement("DELETE FROM test_c3p0 WHERE id < ?");
PreparedStatement stmtUpdate = conn.prepareStatement("UPDATE test_c3p0 SET name = ? WHERE id = ?");
PreparedStatement stmtSelect = conn.prepareStatement("SELECT * FROM test_c3p0")) {
conn.setAutoCommit(false);
stmtCreate.execute();
for (int i = 0; i < 10; i++) {
stmtInsert.setInt(1, i);
stmtInsert.setString(2, "test_insert" + i);
stmtInsert.executeUpdate();
}
stmtDelete.setInt(1, 5);
stmtDelete.executeUpdate();
stmtUpdate.setString(1, "test_update");
stmtUpdate.setInt(2, 5);
stmtUpdate.executeUpdate();
ResultSet rs = stmtSelect.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
rs.close();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Connection getConnection() throws Exception {
ComboPooledDataSource cpds = new ComboPooledDataSource("oceanbase");
return cpds.getConnection();
}
}
References
For more information about OceanBase Connector/J, see OceanBase JDBC driver.