This topic introduces how to build an application by using a Proxool connection pool, MySQL Connector/J, and OceanBase Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, data deletion, data updating, and data query.
Click to download the proxool-mysql-client sample project Prerequisites
You have installed OceanBase Database and created a MySQL tenant.
You have installed JDK 1.8 and Maven.
You have installed IntelliJ IDEA.
Note
The tool used to run the sample code in this topic is IntelliJ IDEA Community Edition 2021.3.2. You can also choose a tool of your preference to run the sample code.
Procedure
Note
The steps outlined in this topic are for the Windows environment. If you are using a different operating system or compiler, the steps may vary slightly.
- Import the
proxool-mysql-clientproject into IntelliJ IDEA. - Obtain the URL of OceanBase Database.
- Modify the database connection information in the
proxool-mysql-clientproject. - Run the
proxool-mysql-clientproject.
Step 1: Import the proxool-mysql-client project into IntelliJ IDEA
Start IntelliJ IDEA.
On the welcome page, click Open, navigate to the directory where the project is located, select the root directory of the project, and click OK.

IntelliJ IDEA automatically detects the project type and loads the project.
Note
When you import a Maven project using IntelliJ IDEA, it will automatically detect the
pom.xmlfile in the project, download the required dependency libraries based on the described dependencies in the file, and add them to the project.
(Optional) Manually import the unresolvable dependencies.
If the dependencies in the
pom.xmlfile are automatically imported to the project, ignore this step.The Sync pane of IntelliJ IDEA indicates that the
proxool-cglibandproxooldependencies are unresolvable. The.jarfiles of theproxool-cglibandproxooldependencies are located in thelibfolder of the root directory of theproxool-mysql-clientproject. Perform the following steps to add these files to the project:- In IntelliJ IDEA, choose File > Project Structure.
- In the left-side pane, click Modules.
- In the right-side pane, click the Dependencies tab. On this tab, click + and choose JARs or directories.
- In the dialog box that appears, navigate to the
libdirectory where the.jarfiles are stored, select the.jarfiles, and click OK. - The added
.jarfiles appear in the list on the Dependencies tab. - Click Apply or OK to save the changes.

Step 2: Obtain the URL of OceanBase Database
Contact the deployment personnel or administrator of OceanBase Database to obtain the corresponding database connection string.
Here is an example:
obclient -hxxx.xxx.xxx.xxx -P2881 -utest_user001@mysql001 -p****** -Dtest -AFor more information about the connection string, see Connect to an OceanBase tenant by using OBClient.
Fill in the URL below based on the OceanBase Database connection string.
jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$passwordParameter description:
$host: the IP address for connecting to OceanBase Database. For connection through OceanBase Database Proxy (ODP), use the IP address of an ODP. For direct connection, use the IP address of an OBServer node.$port: the port for connecting to OceanBase Database. For connection through ODP, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase Database is deployed.$database_name: the name of the database to be accessed.Notice
The user used to connect to the tenant must have the
CREATE,INSERT,DELETE,UPDATE, andSELECTprivileges on the database. For more information about user privileges, see Privilege types in MySQL mode.user_name: the tenant connection account. For connection through ODP, the format isusername@tenant name#cluster nameorcluster name:tenant name:username. For direct connection, the format isusername@tenant name.password: the password of the account.
For more information about the connection properties of MySQL Connector/J, see Configuration Properties.
Here is an example:
jdbc:mysql://xxx.xxx.xxx.xxx:2881/test?user=test_user001@mysql001&password=******
Step 3: Modify the database connection information in the proxool-mysql-client project
Modify the database connection information in the proxool-mysql-client/src/main/resources/db.properties file based on the information obtained in Step 2: Obtain the URL of OceanBase Database.
Here is an example:
- The IP address of the OBServer node is
xxx.xxx.xxx.xxx. - The port is 2881.
- The name of the database to be accessed is
test. - The tenant connection account is
test_user001@mysql001. Here,mysql001is a MySQL user tenant created in OceanBase Database, andtest_user001is the username of themysql001tenant. - The password is
******.
Sample code:
...
jdbc-1.proxool.driver-url=jdbc:mysql://xxx.xxx.xxx.xxx:2881/test?useSSL=false
jdbc-1.user=test_user@mysql001
jdbc-1.password=******
...
Step 4: Run the proxool-mysql-client project
In the project navigation bar, locate and expand the src/main/java/com.example directory.
Right-click the Main file and choose Run 'Main.main()'.
IntelliJ IDEA automatically compiles and runs the project, and displays the output results in the run panel.

You can also execute the following SQL statement in OBClient to view the results.
obclient [(none)]> SELECT * FROM test.test_proxool;The return result is as follows:
+------+---------------+ | c1 | c2 | +------+---------------+ | 6 | test_update | | 7 | test_insert7 | | 8 | test_insert8 | | 9 | test_insert9 | | 10 | test_insert10 | +------+---------------+ 5 rows in set
Project code introduction
Click proxool-mysql-client to download the project code, which is a compressed package named proxool-mysql-client.zip.
After decompressing it, you will find a folder named proxool-mysql-client. The directory structure is as follows:
proxool-mysql-client
├── lib
│ ├── proxool-0.9.1.jar
│ └── proxool-cglib.jar
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── Main.java
│ └── resources
│ └── db.properties
└── pom.xml
File description:
lib: the directory for storing the dependency library files required by the project.proxool-0.9.1.jar: library files of the Proxool connection pool.proxool-cglib.jar: CGLib library files that support the Proxool connection pool.src: the root directory for source code.main: the main code directory, containing the core logic of the application.java: the directory for storing the Java source code.com: the directory for storing the Java package.example: the directory for storing the packages of the sample project.Main.java: a sample main class file that includes logic for creating tables, inserting, deleting, updating, and querying data.resources: the directory for storing resource files, including configuration files.db.properties: the configuration file of the connection pool, containing relevant database connection parameters.pom.xml: the configuration file of the Maven project, used for managing project dependencies and build settings.
Introduction to the pom.xml file
The pom.xml file is the configuration file of the Maven project, which 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 the projects.
The pom.xml file in this topic mainly includes the following sections:
Declaration statement.
The XML file is declared as an XML file that uses XML standard
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure namespaces and the 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.0, and 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 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 group ascom.example. - Use
<artifactId>to specify the project name asproxool-mysql-client. - Use
<version>to specify the project version as1.0-SNAPSHOT.
Sample code:
<groupId>com.example</groupId> <artifactId>proxool-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>- Use
Configure the properties of the project's source file.
Specify the Maven compiler plugin as
maven-compiler-plugin, and set both the source code and target Java versions 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 execution.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 on which the project depends.
Define the dependencies using
<dependency>:Add the
mysql-connector-javalibrary for connecting to and operating the database, and configure the following parameters:- Use
<groupId>to specify the dependency group asmysql. - Use
<artifactId>to specify the dependency name asmysql-connector-java. - Use
<version>to specify the dependency version as5.1.47.
Sample code:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>- Use
Add the
proxool-cglibdependency library, which is a CGLib library for the Proxool connection pool:- Use
<groupId>to specify the dependency group asproxool. - Use
<artifactId>to specify the dependency name asproxool-cglib. - Use
<version>to specify the dependency version as0.9.1.
Sample code:
<dependency> <groupId>proxool</groupId> <artifactId>proxool-cglib</artifactId> <version>0.9.1</version> </dependency>- Use
Add the
proxooldependency library, which is the core library of the Proxool connection pool:- Use
<groupId>to specify the dependency group asproxool. - Use
<artifactId>to specify the dependency name asproxool. - Use
<version>to specify the dependency version as0.9.1.
Sample code:
<dependency> <groupId>proxool</groupId> <artifactId>proxool</artifactId> <version>0.9.1</version> </dependency>- Use
Add the
commons-loggingdependency library, which is a general logging library for recording logs in applications:- Use
<groupId>to specify the dependency group ascommons-logging. - Use
<artifactId>to specify the dependency name ascommons-logging. - Use
<version>to specify the dependency version as1.2.
Sample code:
<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency>- Use
db.properties code
The db.properties file is a connection pool configuration file used in the examples in this topic.
Note
When you use a .properties file to configure a Proxool connection pool, you must follow these rules:
- Use a custom name prefixed with
jdbcto identify each connection pool. This name uniquely identifies each connection pool. - Use a custom name prefixed with
proxool.to identify the attributes of the Proxool connection pool. These attributes are used to configure the properties of the connection pool. - Attributes without a name prefixed with
jdbcwill be ignored and will not be used by the Proxool connection pool. - Attributes without a name prefixed with
proxool.will be passed to the actual database connection, that is, to the actual database driver.
The db.properties file in this topic is an example of a properties file that configures the connection pool for a data source named jdbc-1. The file contains the following sections:
Set an alias for the data source,
TEST.Sample code:
jdbc-1.proxool.alias=TESTConfigure the database connection parameters.
- Set the driver class name. Here, the class name of the MySQL JDBC driver,
com.mysql.jdbc.Driver, is used. - Set the database connection URL, which includes the host IP address, port number, database name, and additional connection properties.
- Set the database username.
- Set the database password.
Sample code:
jdbc-1.proxool.driver-class=com.mysql.jdbc.Driver jdbc-1.proxool.driver-url=jdbc:mysql://$host:$port/$database_name?useSSL=false jdbc-1.user=$user_name jdbc-1.password=$passwordParameter description:
$host: the IP address for connecting to OceanBase Database. For connection through ODP, use the IP address of an ODP. For direct connection, use the IP address of an OBServer node.$port: the port for connecting to OceanBase Database. For connection through ODP, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase Database is deployed.$database_name: the name of the database to be accessed.$user_name: the tenant account. For connection through ODP, the tenant account can be in theusername@tenant name#cluster nameorcluster name:tenant name:usernameformat. For direct connection, the tenant account is in theusername@tenant nameformat.$password: the password of the account.
- Set the driver class name. Here, the class name of the MySQL JDBC driver,
Configure other parameters of the Proxool connection pool.
- Set the maximum connection count to 8.
- Set the minimum connection count to 5.
- Set the available connection count to 4.
- Set the verbose mode to on, that is, enable more log output.
- Set the statistics recording cycle to 10 seconds, 1 minute, and 1 day.
- Set the statistics log level to the error level.
Sample code:
jdbc-1.proxool.maximum-connection-count=8 jdbc-1.proxool.minimum-connection-count=5 jdbc-1.proxool.prototype-count=4 jdbc-1.proxool.verbose=true jdbc-1.proxool.statistics=10s,1m,1d jdbc-1.proxool.statistics-log-level=error
Note
The specific attribute (parameter) configurations depend on project requirements and database characteristics. We recommend that you adjust and configure the attributes based on your actual situation. For more information about Proxool connection pool attributes, see Properties.
Commonly used attribute descriptions:
Attribute |
Default value |
Description |
|---|---|---|
| alias | N/A | The alias of the connection pool. This attribute uniquely identifies a connection pool. |
| driver-class | N/A | The name of the database driver class. |
| driver-url | N/A | The URL of the database connection, which includes the host IP address, port number, database name, and optional database driver parameters. |
| username | N/A | The database username. |
| password | N/A | The database password. |
| maximum-connection-count | 15 | The maximum connection count of the connection pool. The default value is 15, indicating that the connection pool can create at most 15 connections. |
| minimum-connection-count | 5 | The minimum connection count of the connection pool. The default value is 5, indicating that the connection pool will always maintain at least five connections. |
| prototype-count | 0 | The prototype connection count of the connection pool. The default value is 0, indicating that the connection pool will not proactively create extra connections. |
| verbose | false | The detailed output mode of the connection pool. The default value is false, indicating quiet mode.When the verbose attribute is set to true, the connection pool will output more detailed information to assist developers in debugging and monitoring. This information may include the status of the connection pool, connection creation and release, and connection usage.Enabling the verbose mode helps developers better understand the operation of the connection pool and check whether connection allocation and recycling are functioning properly. This is useful for troubleshooting connection leaks, performance issues, and optimization.In production environments, it is generally not recommended to set the verbose attribute to true, as it can generate a large amount of output, potentially impacting system performance and log file size. It is usually recommended to set the verbose attribute to false and enable it only temporarily for debugging and monitoring as needed. |
| statistics | null | The sampling length for statistics, which indicates the usage status of the connection pool. The sampling length can be set to a comma-separated list of time units. For example, 10s,15m indicates sampling every 10 seconds and every 15 minutes. Valid units are s (seconds), m (minutes), h (hours), and d (days). The default value is null, indicating that no statistics are collected.When the statistics attribute is set, the connection pool will periodically sample statistics such as the number of active connections, idle connections, and connection requests. The sampling length determines the granularity and frequency of the statistics. |
| statistics-log-level | null | The log level, or the type of log statistics tracking, for statistics. Valid log levels are DEBUG, INFO, WARN, ERROR, and FATAL. The default value is null, indicating that statistics logs are not recorded.When the statistics-log-level attribute is set, the connection pool will record the generated statistics at the specified log level. These statistics can include the status of the connection pool, connection creation and release, and connection usage. |
| test-after-use | N/A | Whether to test a connection after it is closed. If this attribute is set to true and the house-keeping-test-sql attribute is defined, each connection will be tested after it is closed, that is, returned to the connection pool. If the connection test fails, the connection will be discarded.Connections in the connection pool are usually returned for reuse after use. The purpose of the test-after-use attribute is to test a connection after it is returned to the connection pool to ensure its availability and validity. Connection tests are generally performed using the SQL statement specified by the house-keeping-test-sql attribute.By enabling the test-after-use feature, the connection pool can promptly detect unavailable connections and remove them from the pool to prevent applications from obtaining invalid connections. This improves application stability and reliability.Note that to use the test-after-use feature, you must first set the house-keeping-test-sql attribute to define the SQL statement for connection testing. This way, the connection pool can test and determine connections based on the rules defined by house-keeping-test-sql. |
| house-keeping-test-sql | N/A | The SQL statement for testing idle connections in the connection pool. When the garbage collection thread of the connection pool finds idle connections, it will test these connections using the specified SQL statement. The SQL statement for testing should be a very fast query, such as checking the current date. If this attribute is not defined, connection testing is not performed. In MySQL mode, you can use SELECT CURRENT_DATE or SELECT 1. In Oracle mode, you can use SELECT sysdate FROM DUAL or SELECT 1 FROM DUAL. |
| trace | false | Whether to log the execution of each SQL call. If set to true, each SQL call will be recorded in the log at the DEBUG level and will show the execution time. You can also obtain this information by registering a ConnectionListener (see ProxoolFacade). The default value is false.Enabling the trace feature can generate a large amount of log output, especially under high concurrency and frequent SQL calls. In production environments, use it with caution to avoid excessive logging and unnecessary impact on system performance. |
| maximum-connection-lifetime | 4 hours | The maximum lifecycle of a connection. In other words, the longest time a connection can exist from creation to destruction (in milliseconds). The default value is 4 hours. The lifecycle of a connection refers to the period from its creation to its destruction. By setting the maximum-connection-lifetime attribute, you can limit the maximum time a connection can exist in the connection pool to prevent it from being idle for too long or causing resource leaks. |
| maximum-active-time | 5 minutes | The maximum active time of a thread. If the garbage collection thread of the connection pool finds that a thread has been active for longer than the specified period, it will terminate the thread. Therefore, make sure that this attribute is set to a value greater than the expected minimum response time. The default value is 5 minutes. The garbage collection thread will terminate excess available threads in the connection pool (threads that are not in use and have been idle for longer than the specified period). The number of threads retained will be the minimum connection count specified by the minimum-connection-count attribute. The garbage collection thread will check the connection pool at intervals defined by the house-keeping-sleep-time attribute. |
| maximum-new-connections | N/A | The maximum number of new connections established at a time by the connection pool. This attribute is deprecated. We recommend that you use the simultaneous-build-throttle attribute instead. |
| simultaneous-build-throttle | 10 | The maximum number of new connections established simultaneously by the connection pool. In other words, the upper limit of new connections that are being established but not yet available. The establishment of connections may use multiple threads, such as when connections are needed on demand. There is also a delay between the decision to establish a connection and the availability of the connection. Therefore, we need a way to ensure that not too many threads are deciding to establish connections at the same time. The simultaneous-build-throttle attribute limits the number of new connections established simultaneously by the connection pool to control its concurrency. When the maximum concurrent connection count is reached, threads requesting new connections will be blocked until an available connection becomes available or the specified timeout period elapses.By setting an appropriate value for the simultaneous-build-throttle attribute, you can balance the concurrency of the connection pool and its resource consumption. The default value is 10, indicating that the connection pool can establish a maximum of 10 connections at a time. |
| overload-without-refusal-lifetime | 60 | A parameter used to help determine the status of the connection pool. If connection requests are rejected within the specified time threshold (in milliseconds), the connection pool is considered overloaded. The default value is 60,000 ms. |
| test-before-use | N/A | Whether to test each connection before it is provided. If this attribute is set to true, before a connection is provided to an application, it will be tested by executing the predefined test SQL statement (defined by the house-keeping-test-sql attribute). If the connection test fails, the connection will be discarded and another available connection will be selected. If all connections fail the test, a new connection will be created. If the new connection also fails the test, a SQLException will be thrown.Note that for a MySQL database, you must also add the autoReconnect=true parameter to the connection parameters. Otherwise, even if the test-before-use parameter is enabled, reconnection cannot be performed. |
| fatal-sql-exception | null | A comma-separated list of message fragments used to detect and handle SQL exceptions. When an SQLException occurs, its message is compared with these message fragments. If it contains any of the message fragments (case-sensitive), it is considered a fatal SQL exception. This will cause the connection to be discarded. Regardless of the situation, the exception will be rethrown to inform users of the issue. You can also configure different exceptions to be thrown (see fatal-sql-exception-wrapper-class). The default value is null. Note that if you configure the fatal-sql-exception-wrapper-class attribute, you can specify an alternative exception class to throw. This allows you to customize the handling of SQL exceptions. |
| fatal-sql-exception-wrapper-class | null | The exception wrapper for fatal SQL exceptions. When the fatal-sql-exception attribute is configured, the default behavior is to discard the exception that causes the fatal SQLException and directly throw the original exception to the user. With this attribute, you can wrap SQLException in another exception. This exception can be any class that inherits from SQLException or RuntimeException. Proxool provides two classes for your use: FatalSQLException and FatalRuntimeException. To use these classes, you can set this attribute to org.logicalcobwebs.proxool.FatalSQLException or org.logicalcobwebs.proxool.FatalRuntimeException based on your needs. The default value is null, indicating that fatal SQLException will not be wrapped. Note that the exception wrapper class must be a subclass of SQLException or RuntimeException. |
| house-keeping-sleep-time | 30 seconds | The sleep time of the maintenance thread (house keeping thread) of the connection pool. The maintenance thread is responsible for checking the status of all connections and determining whether to destroy or create connections. The default value is 30 seconds, indicating that the maintenance thread will perform maintenance tasks every 30 seconds. |
| injectable-connection-interface | N/A | Allows Proxool to implement methods defined in the Connection object. |
| injectable-statement-interface | N/A | Allows Proxool to implement methods defined in the Statement object. |
| injectable-prepared-statement-interface | N/A | Allows Proxool to implement methods defined in the PreparedStatement object. |
| injectable-callable-statement-interface | N/A | Allows Proxool to implement methods defined in the CallableStatement object. |
| jndi-name | N/A | The name registered by the connection pool in the Java Naming and Directory Interface (JNDI). |
Introduction to Main.java
The Main.java file is part of the sample application and demonstrates how to obtain a database connection from a Proxool connection pool and perform a series of database operations, including table creation, data insertion, data deletion, data updating, data query, and result printing.
The code of the Main.java file in this topic is mainly divided into the following sections:
Import the required classes and interfaces.
Define the package where the code is located and import the classes related to Proxool and JDBC. These classes are used to configure and manage the database connection pool and execute SQL statements. By using the Proxool connection pool, the performance and reliability of database operations are improved. The specific steps are as follows:
- Define the
com.examplepackage, which stores the current Java class. - Import the
org.logicalcobwebs.proxool.configuration.PropertyConfiguratorclass of Proxool. - Import the
java.io.InputStreamclass for reading configuration files. - Import the
java.sql.Connectionclass of JDBC. - Import the
java.sql.DriverManagerclass of JDBC. - Import the
java.sql.ResultSetclass of JDBC. - Import the
java.sql.Statementclass of JDBC. - Import the
java.util.Propertiesclass for loading configuration files.
Sample code:
package com.example; import org.logicalcobwebs.proxool.configuration.PropertyConfigurator; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties;- Define the
Define the class name and methods.
Define the main method of a Java program, which obtains database connection information by reading the configuration file. After establishing a database connection using the Proxool driver, it calls predefined methods to execute DDL, DML, and query statements in sequence. It captures and prints the exception information that may occur. The purpose of this code is to perform database-related operations and record logs by using a log recorder. The specific steps are as follows:
Define a public class named Main.
Define a private static constant named
DB_PROPERTIES_FILE, which indicates the path of the database (attribute) file. This constant can be referenced in the code to load and read the attribute file.Define a public static method named
main, which serves as the starting execution point of the program.A code block that captures possible exceptions.
- Create a
Propertiesobject to read attributes from the configuration file. - Use the class loader of the Main class to obtain the input stream of the configuration file.
- Load the configuration file by using the loaded input stream and load the attributes into the
Propertiesobject. - Configure the connection pool by using the loaded attributes.
- Dynamically load the Proxool database driver.
- Establish a database connection by using the Proxool driver.
- Create a
Statementobject. - Call the predefined method
executeDDLStatements()to execute DDL statements for creating a table. In this example, the table name istest_proxool. - Call the predefined method
executeDMLStatements()to execute DML statements for inserting, updating, and deleting data. - Call the predefined method
executeQueryStatements()to execute query statements for querying data.
- Create a
Capture and print the exception information that may occur.
Define a method for creating a table.
Sample code:
public class Main { private static final String DB_PROPERTIES_FILE = "/db.properties"; public static void main(String[] args) { try { Properties properties = new Properties(); InputStream is = Main.class.getResourceAsStream(DB_PROPERTIES_FILE); properties.load(is); PropertyConfigurator.configure(properties); Class.forName("org.logicalcobwebs.proxool.ProxoolDriver"); try (Connection conn = DriverManager.getConnection("proxool.TEST"); Statement stmt = conn.createStatement()) { executeDDLStatements(stmt); executeDMLStatements(stmt); executeQueryStatements(stmt); } } catch (Exception e) { e.printStackTrace(); } } // Define a method for creating a table. // Define a method for executing DML statements. // Define a method for querying data. }Define a method for creating a table.
Define a private static method named
executeDDLStatements()to execute DDL statements, including statements for creating a table. The specific steps are as follows:- Define a private static method named
executeDDLStatements(), which accepts aStatementobject as the parameter and may throw anException. - Use the
execute()method to execute SQL statements to create a table namedtest_proxool. The table contains two columns:c1of theINTtype andc2of theVARCHAR(32)type.
Sample code:
private static void executeDDLStatements(Statement stmt) throws Exception { stmt.execute("CREATE TABLE test_proxool (c1 INT, c2 VARCHAR(32))"); }- Define a private static method named
Define a method for executing DML statements.
Define a private static method named
executeDMLStatements()to execute DML statements, which include statements for inserting data, updating data, and deleting data. The specific steps are as follows:- Define a private static method named
executeDMLStatements(), which accepts aStatementobject as the parameter and may throw anExceptionwhen an exception occurs during execution. - Use a
forloop to iterate from 1 to 10. In the loop, use theexecute()method to execute an SQL insert statement to insert the variableiand the related string value into thetest_proxooltable. - Execute an SQL delete statement to delete rows where the value of column
c1is less than or equal to 5 from thetest_proxooltable. - Execute an SQL update statement to update the value of column
c2totest_updatefor the row where the value of columnc1is 6 in thetest_proxooltable.
Sample code:
private static void executeDMLStatements(Statement stmt) throws Exception { for (int i = 1; i <= 10; i++) { stmt.execute("INSERT INTO test_proxool VALUES (" + i + ",'test_insert" + i + "')"); } stmt.execute("DELETE FROM test_proxool WHERE c1 <= 5"); stmt.execute("UPDATE test_proxool SET c2 = 'test_update' WHERE c1 = 6"); }- Define a private static method named
Define a method for querying data.
Define a private static method named
executeQueryStatements()to executeSELECTstatements and process the query results. The specific steps are as follows:- Define a private static method named
executeQueryStatements(), which accepts aStatementobject as the parameter and may throw anExceptionwhen an exception occurs during execution. - Use the
executeQuery()method to execute aSELECTstatement and store the query result in theResultSetobjectrs. In this example, all data in thetest_proxooltable is queried. Use thetry-with-resourcesstatement to ensure that theResultSetis automatically closed after it is used. In this example, theResultSetis thersobject. - Use a
whileloop and thenext()method to iterate through each row of data in theResultSetobjectrs. In each iteration, thers.next()method moves the pointer to the next row in the result set. If there is another row available, the method returnstrue; otherwise, it returnsfalse. In thewhileloop, as long asrs.next()returnstrue, there are more rows available. The code in the loop body is executed, and the data of the current row is processed. After all rows of data are processed,rs.next()returnsfalse, and the loop ends. - Use the
getInt()andgetString()methods to obtain the values of specified columns in the current row and print them to the console. In this example, the values of thec1andc2columns are printed. ThegetInt()method is used to obtain an integer value, and thegetString()method is used to obtain a string value.
Sample code:
private static void executeQueryStatements(Statement stmt) throws Exception { try (ResultSet rs = stmt.executeQuery("SELECT * FROM test_proxool")) { while (rs.next()) { System.out.println(rs.getInt("c1") + " " + rs.getString("c2")); } } }- Define a private static method named
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.oceanbase</groupId>
<artifactId>proxool-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>proxool</groupId>
<artifactId>proxool-cglib</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>proxool</groupId>
<artifactId>proxool</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
#alias: the alias of the data source
jdbc-1.proxool.alias=TEST
#driver-class: driver name
jdbc-1.proxool.driver-class=com.mysql.jdbc.Driver
#driver-url: url connection string, username and password must be determined
jdbc-1.proxool.driver-url=jdbc:mysql://$host:$port/$database_name?useSSL=false
jdbc-1.user=$user_name
jdbc-1.password=$password
#The maximum number of database connections. The default is 15
jdbc-1.proxool.maximum-connection-count=8
#The minimum number of database connections, defaults to 5
jdbc-1.proxool.minimum-connection-count=5
#The number of available connections in the Connection pool. If the number of connections in the current Connection pool is less than this value, new connections will be established (assuming that the maximum number of available connections is not exceeded). For example, if we have three active connections and two available connections, and our prototype count is 4, the database Connection pool will try to establish another two connections. This is different from the minimum connection count Minimum connection count also counts active connections. Prototype count is the number of spare connections
jdbc-1.proxool.prototype-count=4
#verbose: detailed information settings. Parameter bool value
jdbc-1.proxool.verbose=true
#statistics: connection pool usage statistics. Parameter "10s, 1m, 1d"
jdbc-1.proxool.statistics=10s,1m,1d
#statistics-log-level: log statistics tracking type. Parameter 'ERROR' or 'INFO'
jdbc-1.proxool.statistics-log-level=error
package com.example;
import org.logicalcobwebs.proxool.configuration.PropertyConfigurator;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class Main {
private static final String DB_PROPERTIES_FILE = "/db.properties";
public static void main(String[] args) {
try {
Properties properties = new Properties();
InputStream is = Main.class.getResourceAsStream(DB_PROPERTIES_FILE);
properties.load(is);
PropertyConfigurator.configure(properties);
Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
try (Connection conn = DriverManager.getConnection("proxool.TEST");
Statement stmt = conn.createStatement()) {
executeDDLStatements(stmt);
executeDMLStatements(stmt);
executeQueryStatements(stmt);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void executeDDLStatements(Statement stmt) throws Exception {
stmt.execute("CREATE TABLE test_proxool (c1 INT, c2 VARCHAR(32))");
}
private static void executeDMLStatements(Statement stmt) throws Exception {
for (int i = 1; i <= 10; i++) {
stmt.execute("INSERT INTO test_proxool VALUES (" + i + ",'test_insert" + i + "')");
}
stmt.execute("DELETE FROM test_proxool WHERE c1 <= 5");
stmt.execute("UPDATE test_proxool SET c2 = 'test_update' WHERE c1 = 6");
}
private static void executeQueryStatements(Statement stmt) throws Exception {
try (ResultSet rs = stmt.executeQuery("SELECT * FROM test_proxool")) {
while (rs.next()) {
System.out.println(rs.getInt("c1") + " " + rs.getString("c2"));
}
}
}
}
Related information
- For more information about MySQL Connector/J, see Overview of MySQL Connector/J.
- For more information about the Proxool connection pool, see Introduction for Users.
