Sample program for connecting to an OceanBase database using a Druid connection pool
This topic describes how to build an application that connects to an OceanBase database using a Druid connection pool and MySQL Connector/J. The application performs basic database operations, such as creating tables, inserting data, updating data, deleting data, querying data, and dropping tables.
Click to download the druid-mysql-client sample project
Prerequisites
You have installed OceanBase Database and created a MySQL-mode tenant.
You have installed JDK 1.8 and Maven.
You have installed Eclipse.
NoteThe tool used to run the code in this topic is Eclipse IDE for Java Developers version 2022-03. You can also use other tools to run the sample code.
Procedure
The steps provided in this topic are for compiling and running the project in a Windows environment using Eclipse IDE for Java Developers version 2022-03. The steps may vary slightly if you use a different operating system or compiler.
Import the
druid-mysql-clientproject into Eclipse.Obtain the OceanBase database URL.
Modify the database connection information in the
druid-mysql-clientproject.Run the
druid-mysql-clientproject.
Step 1: Import the druid-mysql-client project into Eclipse
Open Eclipse. On the menu bar, choose File > Open Projects from File System.
In the dialog box that appears, click the Directory button to 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 in the project, downloads the required dependency libraries based on the dependencies described in the file, and adds them to the project.
View the project status.

Step 2: Obtain 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 Obtain connection parameters.
Use the information from the OceanBase database connection string to complete the following URL.
jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$password&useSSL=falseParameter description:
$host: The domain name for the OceanBase database connection.$port: The OceanBase database connection port. The default port for a MySQL-mode tenant is 3306.$database_name: The name of the database to access.$user_name: The connection account for the tenant.$password: The 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=******&useSSL=false
Step 3: Modify the database connection information in the druid-mysql-client project
Modify the database connection information in the druid-mysql-client/src/main/resources/db.properties file based on the information obtained in 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 connection account for the tenant is
test_user001.The password is
******.
The code is as follows:
...
url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?useSSL=false
username=test_user001
password=******
...
Step 4: Run the druid-mysql-client project
In the Project Explorer view, find and expand the druid-mysql-client/src/main/java directory.
Right-click the Main.java file, and then choose Run As > Java Application.
View the output in the Eclipse console window.

Project code overview
Click druid-mysql-client to download the project code. The downloaded file is a compressed package named druid-mysql-client.zip.
After you decompress the package, a folder named druid-mysql-client is created. The directory structure is as follows:
druid-mysql-client
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── Main.java
│ └── resources
│ └── db.properties
└── pom.xml
File description:
src: The root directory for the source code.main: The main code directory, which contains the 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 inserting, deleting, updating, and querying data.resources: The resource file directory, which contains configuration files.db.properties: The configuration file for the connection pool. It contains parameters related to the database connection.pom.xml: The configuration file for the Maven project. It is used to manage project dependencies and build settings.
pom.xml code overview
pom.xml 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 can automatically download dependencies, compile, and package projects.
The code in the pom.xml file in this topic includes the following main parts:
File declaration statement.
This statement declares that the file is an XML file, the XML version is
1.0, and the character encoding isUTF-8.The code is as follows:
<?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.
The code is as follows:
<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 asdruid-mysql-client.The
<version>element specifies the project's version number as1.0-SNAPSHOT.
The code is as follows:
<groupId>com.example</groupId> <artifactId>druid-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>Configure the properties of the project source files.
This configuration specifies the Maven compiler plugin as
maven-compiler-pluginand sets both the source and target Java versions to 8. This means that the project's source code is written using Java 8 features, and the compiled bytecode is compatible with the Java 8 runtime environment. This setting ensures that the project can correctly handle Java 8 syntax and features during compilation and runtime.NoteJava 1.8 and Java 8 are different names for the same version.
The code is as follows:
<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.
Add the
mysql-connector-javadependency library, which is used to interact with the database: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.40.
The code is as follows:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency>Add the
druiddependency library:The
<groupId>element specifies the dependency's organization ascom.alibaba.The
<artifactId>element specifies the dependency's name asdruid.The
<version>element specifies the dependency's version number as1.2.8.
The code is as follows:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency>
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 database URL, username, password, and other optional connection pool settings.
The code in the db.properties file in this topic includes the following main parts:
Configure database connection parameters.
Set the database driver class name to
com.oceanbase.jdbc.Driver.Specifies the URL for the database connection, including the host IP address, port number, and schema to access.
Specifies the database username.
Specifies the database password.
The code is as follows:
driverClassName=com.oceanbase.jdbc.Driver url=jdbc:oceanbase://$host:$port/$database_name?useSSL=false username=$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 connection account for the tenant.$password: The account password.
Configure other connection pool parameters.
Specifies the SQL statement to validate the connection as
select 1.Specifies the initial number of connections in the pool as 3. This means that when the connection pool starts, it creates 3 initial connections.
Specifies the maximum number of active connections in the pool as 30. This means that the pool can have a maximum of 30 concurrent connections.
Specifies whether to log abandoned connections as
true. This means that when an abandoned connection is recycled, information is written to the error log. You can set this totruein a staging environment and tofalsein an online environment to prevent performance impact.Specifies the minimum number of idle connections in the pool as 5. This means that when the number of idle connections drops below 5, the pool automatically creates new connections.
Specifies the maximum wait time for a connection as 1000 milliseconds. This means that if all connections in the pool are in use, a request for a connection throws a timeout exception after waiting for 1000 milliseconds.
Specifies the minimum idle time for a connection as 300000 milliseconds. This means that a connection is recycled if it is idle for 300000 milliseconds (5 minutes).
Specifies whether to recycle abandoned connections as
true. This means that a connection is recycled if it exceeds the time defined byremoveAbandonedTimeout.Specifies the timeout for abandoned connections as 300 seconds. This means that a connection that has not been used for 300 seconds (5 minutes) is recycled.
Specifies the run interval for the idle connection recycling thread as 10000 milliseconds. This means that the thread runs every 10000 milliseconds (10 seconds) to recycle idle connections.
Specifies whether to validate a connection's availability when it is borrowed as
false. Setting this tofalsecan improve performance, but may result in borrowing an invalid connection.Specifies whether to validate a connection's availability when it is returned as
false. Setting this tofalsecan improve performance, but may result in returning an invalid connection.Specifies whether to validate a connection while it is idle as
true. When set totrue, the connection pool periodically runsvalidationQueryto validate the connection's availability.Specifies whether to enable the persistent connection keepalive feature as
false. Setting this tofalsedisables persistent connection keepalive.Specifies the idle time threshold for connections as 60000 milliseconds. If a connection's idle time exceeds this threshold of 60000 milliseconds (1 minute), the keepalive mechanism checks the connection to ensure its availability. If any operation occurs on the connection within the threshold, the idle time is recalculated.
The code is as follows:
validationQuery=select 1 initialSize=3 maxActive=30 logAbandoned=true minIdle=5 maxWait=1000 minEvictableIdleTimeMillis=300000 removeAbandoned=true removeAbandonedTimeout=300 timeBetweenEvictionRunsMillis=10000 testOnBorrow=false testOnReturn=false testWhileIdle=true keepAlive=false keepAliveBetweenTimeMillis=60000
The specific property (parameter) configuration depends on your project requirements and database characteristics. Adjust the configuration as needed.
Common configuration parameters for the Druid connection pool:
Parameter |
Description |
url |
Specifies the URL for connecting to the database, including the database type, hostname, port number, and database name. |
username |
Specifies the username required to connect to the database. |
password |
Specifies the password required to connect to the database. |
driverClassName |
Specifies the database driver class name. If you do not explicitly configure |
initialSize |
Specifies the number of connections to create when initializing the connection pool. When the application starts, the connection pool creates the specified number of connections and places them in the pool. |
maxActive |
Specifies the maximum number of active connections in the connection pool. When the number of active connections reaches the maximum value, subsequent connection requests will wait until a connection is released. |
maxIdle |
Specifies the maximum number of idle connections in the connection pool (this property is deprecated). When the number of idle connections reaches the maximum value, excess connections are closed. |
minIdle |
Specifies the minimum number of idle connections in the connection pool. When the number of idle connections drops below the minimum value, the connection pool creates new connections. |
maxWait |
Specifies the maximum time to wait for a connection. An exception is thrown if this time is exceeded. If set to a positive number, it represents the wait time in milliseconds. |
poolPreparedStatements |
Specifies whether to cache |
validationQuery |
Specifies the SQL query statement for connection validation. When a connection is taken from the pool, this query is executed to verify that the connection is valid. |
timeBetweenEvictionRunsMillis |
Specifies the interval, in milliseconds, at which the connection pool checks for idle connections. If a connection's idle time exceeds the value of |
minEvictableIdleTimeMillis |
Specifies the minimum idle time for a connection in the pool, in milliseconds. Connections that are idle longer than this time will be recycled. If set to a negative number, connections are not recycled. |
testWhileIdle |
Specifies whether to test connections while they are idle. If set to |
testOnBorrow |
Specifies whether to test connections when they are borrowed from the pool. If set to |
testOnReturn |
Specifies whether to test connections when they are returned to the pool. If set to |
filters |
Specifies a series of predefined filters in the connection pool. These filters can perform pre-processing and post-processing operations on connections in a specific order to provide additional features and enhance pool performance. Common filters include the following:
By configuring these filters in the |
Main.java code overview
Main.java is the main program for the sample in this topic. This sample shows how to use a data source, connection objects, and various database operation methods to interact with the database.
The code in the Main.java file in this topic includes the following main parts:
Import necessary classes and interfaces.
Declares the package name for the current code as
com.example.Imports the Java
IOExceptionclass to handle input/output exceptions.Imports the Java
InputStreamclass to obtain an input stream from a file or other source.Imports the Java
Connectioninterface, which represents a connection to the database.Imports the Java
ResultSetinterface, which represents the result set of a database query.Imports the Java
SQLExceptionclass to handle SQL exceptions.Imports the Java
Statementinterface to execute SQL statements.Imports the Java
PreparedStatementinterface for precompiled SQL statements.Imports the Java
Propertiesclass to handle properties files.Imports the Java
DataSourceinterface to manage database connections.Imports the
DruidDataSourceFactoryclass from the Alibaba Druid connection pool to create a Druid data source.
The code is as follows:
package com.example; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory;Create a
Mainclass and define themainmethod.This defines a
Mainclass and amainmethod. Themainmethod demonstrates how to use the connection pool to perform a series of operations on the database. The steps are as follows:Define a public class named
Mainas the program's entry point. The class name must match the file name.Define a public static method
mainas the program's entry point, which accepts command-line arguments.Use an exception handling mechanism to catch and handle potential exceptions.
Call the
loadPropertiesFilemethod to load the properties file and return aPropertiesobject.Call the
createDataSource()method to create a data source object based on the configuration in the properties file.Use a
try-with-resourcesstatement to obtain a database connection and automatically close it after use.Call the
createTable()method to create a table.Call the
insertData()method to insert data.Call the
selectData()method to query data.Call the
updateData()method to update data.Call the
selectData()method again to query the updated data.Call the
deleteData()method to delete data.Call the
selectData()method again to query the data after deletion.Call the
dropTable()method to drop the table.
The code is as follows:
public class Main { public static void main(String[] args) { try { Properties properties = loadPropertiesFile(); DataSource dataSource = createDataSource(properties); try (Connection conn = dataSource.getConnection()) { // Create table createTable(conn); // Insert data insertData(conn); // Query data selectData(conn); // Update data updateData(conn); // Query the updated data selectData(conn); // Delete data deleteData(conn); // Query the data after deletion selectData(conn); // Drop table dropTable(conn); } } catch (Exception e) { e.printStackTrace(); } } // Define a method to get and use configuration information from the properties file // Define a method to get the data source object // Define a method to create a table // Define a method to insert data // Define a method to update data // Define a method to delete data // Define a method to query data // Define a method to delete the table }Define a method to obtain and use configuration information from the properties file.
Define a private static method
loadPropertiesFile()to load a properties file and return aPropertiesobject. The steps are as follows:The method is defined as private and static. It returns a
Propertiesobject and declares that it may throw anIOException.Create a
Propertiesobject to store the key-value pairs from the properties file.Use a
try-with-resourcesstatement to obtain the input streamisfor thedb.propertiesfile through the class loader.Use the
loadmethod to load the properties from the input stream into thepropertiesobject.Return the loaded
propertiesobject.
The code is as follows:
private static Properties loadPropertiesFile() throws IOException { Properties properties = new Properties(); try (InputStream is = Main.class.getClassLoader().getResourceAsStream("db.properties")) { properties.load(is); } return properties; }Define a method to obtain the data source object.
The following steps describe the
createDataSource()method, which creates aDataSourceobject based on the configuration in the properties file. This object is used to manage and obtain database connections.The method is defined as private and static. It accepts a
Propertiesobject as a parameter and declares that it may throw anException.Call the
createDataSource()method of theDruidDataSourceFactoryclass, passing thepropertiesto return aDataSourceobject.
The code is as follows:
private static DataSource createDataSource(Properties properties) throws Exception { return DruidDataSourceFactory.createDataSource(properties); }Define a method to create a table.
Define a private static method
createTable()to create a data table in the database:The method is defined as private and static. It accepts a
Connectionobject as a parameter and declares that it may throw anSQLException.Use a
try-with-resourcesstatement to create aStatementobjectstmtby calling thecreateStatement()method of theconnconnection object.Define a string variable
sqlto store the SQL statement for creating the table.Use the
executeUpdate()method to execute the SQL statement and create the data table.Print a success message indicating that the table was created.
The code is as follows:
private static void createTable(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement()) { String sql = "CREATE TABLE test_druid (id INT, name VARCHAR(20))"; stmt.executeUpdate(sql); System.out.println("Table created successfully."); } }Define a method to insert data.
Define a private static method
insertData()to insert data into the database. The method performs the following steps:The method is defined as private and static. It accepts a
Connectionobject as a parameter and declares that it may throw anSQLException.Define a string variable
insertDataSqlto store the SQL statement for inserting data.Define an integer variable
insertedRowswith an initial value of 0 to record the number of inserted rows.Use a
try-with-resourcesstatement to create aPreparedStatementobjectinsertDataStmtusing theprepareStatement()method of theconnconnection object and the insert SQL statement.Use a
forloop to iterate 5 times and insert 5 rows of data.Use the
setInt()method to set the value of the first parameter to the loop variablei.Use the
setString()method to set the value of the second parameter to the stringtest_insertconcatenated with the value of the loop variablei.Use the
executeUpdate()method to execute the insert SQL statement and add the number of affected rows to theinsertedRowsvariable.
Print a success message indicating that data was inserted, along with the total number of inserted rows.
Return the total number of inserted rows.
The code is as follows:
private static int insertData(Connection conn) throws SQLException { String insertDataSql = "INSERT INTO test_druid (id, name) VALUES (?, ?)"; int insertedRows = 0; try (PreparedStatement insertDataStmt = conn.prepareStatement(insertDataSql)) { for (int i = 1; i < 6; i++) { insertDataStmt.setInt(1, i); insertDataStmt.setString(2, "test_insert" + i); insertedRows += insertDataStmt.executeUpdate(); } System.out.println("Data inserted successfully. Inserted rows: " + insertedRows); } return insertedRows; }Define a method to update data.
Define a private static method
updateData()to update data in the database. The steps are as follows:The method is defined as private and static. It accepts a
Connectionobject as a parameter and declares that it may throw anSQLException.Use a
try-with-resourcesstatement to create aPreparedStatementobjectpstmtusing theprepareStatement()method of theconnconnection object and the update SQL statement.Use the
setString()method to set the value of the first parameter to the stringtest_update.Use the
setInt()method to set the value of the second parameter to the integer value 3.Use the
executeUpdate()method to execute the update SQL statement and assign the number of affected rows to theupdatedRowsvariable.Print a success message indicating that data was updated, along with the total number of updated rows.
The code is as follows:
private static void updateData(Connection conn) throws SQLException { try (PreparedStatement pstmt = conn.prepareStatement("UPDATE test_druid SET name = ? WHERE id = ?")) { pstmt.setString(1, "test_update"); pstmt.setInt(2, 3); int updatedRows = pstmt.executeUpdate(); System.out.println("Data updated successfully. Updated rows: " + updatedRows); } }Define a method to delete data.
Define a private static method
deleteData()to delete data from the database. The steps are as follows:The method is defined as private and static. It accepts a
Connectionobject as a parameter and declares that it may throw anSQLException.Use a
try-with-resourcesstatement to create aPreparedStatementobjectpstmtusing theprepareStatement()method of theconnconnection object and the delete SQL statement.Use the
setInt()method to set the value of the first parameter to the integer value 3.Use the
executeUpdate()method to execute the delete SQL statement and assign the number of affected rows to thedeletedRowsvariable.Print a success message indicating that data was deleted, along with the total number of deleted rows.
The code is as follows:
private static void deleteData(Connection conn) throws SQLException { try (PreparedStatement pstmt = conn.prepareStatement("DELETE FROM test_druid WHERE id < ?")) { pstmt.setInt(1, 3); int deletedRows = pstmt.executeUpdate(); System.out.println("Data deleted successfully. Deleted rows: " + deletedRows); } }Define a method to query data.
Define a private static method
selectData()to query data from the database by following these steps:The method is defined as private and static. It accepts a
Connectionobject as a parameter and declares that it may throw anSQLException.Use a
try-with-resourcesstatement to create aStatementobjectstmtby calling thecreateStatement()method of theconnconnection object.Define a string variable
sqlto store the SQL statement for querying data.Use the
executeQuery()method to execute the query SQL statement and assign the returned result set to theresultSetvariable.Use a
whileloop to iterate through each row in the result set.Use the
getInt()method to retrieve the integer value of theidfield for the current row and assign it to theidvariable.Use the
getString()method to retrieve the string value of thenamefield for the current row and assign it to thenamevariable.Print the values of the
idandnamefields for the current row.
The code is as follows:
private static void selectData(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement()) { String sql = "SELECT * FROM test_druid"; ResultSet resultSet = stmt.executeQuery(sql); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); System.out.println("id: " + id + ", name: " + name); } } }Define a method to drop the table.
Define a private static method
dropTable()to drop tables from the database as follows:The method is defined as private and static. It accepts a
Connectionobject as a parameter and declares that it may throw anSQLException.Use a
try-with-resourcesstatement to create aStatementobjectstmtby calling thecreateStatement()method of theconnconnection object.Define a string variable
sqlto store the SQL statement for dropping the table.Use the
executeUpdate()method to execute the SQL statement to drop the table.Print a success message indicating that the table was dropped.
The code is as follows:
private static void dropTable(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement()) { String sql = "DROP TABLE test_druid"; stmt.executeUpdate(sql); System.out.println("Table dropped successfully."); } }
Complete code
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>druid-mysql-client</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>
</project>
db.properties
# Database Configuration
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://$host:$port/$database_name?useSSL=false
username=$user_name
password=$password
# Connection Pool Configuration
# A query to validate connections. For MySQL, you must configure 'select 1'. For Oracle, use 'select 1 from dual'.
validationQuery=select 1
# The initial number of connections.
initialSize=3
# The maximum number of active connections in the connection pool.
maxActive=30
# Specifies whether to log abandoned connections when they are closed. When a connection is recycled, information is printed to the console. Set to true for staging environments and false for online environments to avoid performance impact.
logAbandoned=true
# The minimum number of idle connections.
minIdle=5
# The maximum time to wait for a connection, in milliseconds.
maxWait=1000
# The minimum time a connection can be idle before it is eligible for eviction. The value is in milliseconds.
minEvictableIdleTimeMillis=300000
# Specifies whether to remove abandoned connections that exceed the timeout.
removeAbandoned=true
# The timeout for abandoned connections, in seconds. The current value is 300 seconds (5 minutes). Adjust this value if your business processing time exceeds 5 minutes.
removeAbandonedTimeout=300
# The interval, in milliseconds, between runs of the idle connection eviction thread.
timeBetweenEvictionRunsMillis=10000
# Specifies whether to validate connections when they are borrowed from the pool. Setting to false can improve performance.
testOnBorrow=false
# Specifies whether to validate connections when they are returned to the pool.
testOnReturn=false
# Specifies whether to validate connections while they are idle. If set to true, the pool runs validationQuery on idle connections.
testWhileIdle=true
# Specifies whether to enable the keepalive feature. If set to true, the DestroyConnectionThread checks connections.
keepAlive=false
# The time, in milliseconds, between keepalive checks for a connection.
keepAliveBetweenTimeMillis=60000
Main.java
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class Main {
public static void main(String[] args) {
try {
Properties properties = loadPropertiesFile();
DataSource dataSource = createDataSource(properties);
try (Connection conn = dataSource.getConnection()) {
// Create table
createTable(conn);
// Insert data
insertData(conn);
// Query data
selectData(conn);
// Update data
updateData(conn);
// Query the updated data
selectData(conn);
// Delete data
deleteData(conn);
// Query the data after deletion
selectData(conn);
// Drop table
dropTable(conn);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Properties loadPropertiesFile() throws IOException {
Properties properties = new Properties();
try (InputStream is = Main.class.getClassLoader().getResourceAsStream("db.properties")) {
properties.load(is);
}
return properties;
}
private static DataSource createDataSource(Properties properties) throws Exception {
return DruidDataSourceFactory.createDataSource(properties);
}
private static void createTable(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String sql = "CREATE TABLE test_druid (id INT, name VARCHAR(20))";
stmt.executeUpdate(sql);
System.out.println("Table created successfully.");
}
}
private static int insertData(Connection conn) throws SQLException {
String insertDataSql = "INSERT INTO test_druid (id, name) VALUES (?, ?)";
int insertedRows = 0;
try (PreparedStatement insertDataStmt = conn.prepareStatement(insertDataSql)) {
for (int i = 1; i < 6; i++) {
insertDataStmt.setInt(1, i);
insertDataStmt.setString(2, "test_insert" + i);
insertedRows += insertDataStmt.executeUpdate();
}
System.out.println("Data inserted successfully. Inserted rows: " + insertedRows);
}
return insertedRows;
}
private static void updateData(Connection conn) throws SQLException {
try (PreparedStatement pstmt = conn.prepareStatement("UPDATE test_druid SET name = ? WHERE id = ?")) {
pstmt.setString(1, "test_update");
pstmt.setInt(2, 3);
int updatedRows = pstmt.executeUpdate();
System.out.println("Data updated successfully. Updated rows: " + updatedRows);
}
}
private static void deleteData(Connection conn) throws SQLException {
try (PreparedStatement pstmt = conn.prepareStatement("DELETE FROM test_druid WHERE id < ?")) {
pstmt.setInt(1, 3);
int deletedRows = pstmt.executeUpdate();
System.out.println("Data deleted successfully. Deleted rows: " + deletedRows);
}
}
private static void selectData(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String sql = "SELECT * FROM test_druid";
ResultSet resultSet = stmt.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
}
}
private static void dropTable(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String sql = "DROP TABLE test_druid";
stmt.executeUpdate(sql);
System.out.println("Table dropped successfully.");
}
}
}
References
For more information about MySQL Connector/J, see Overview of MySQL Connector/J.