This topic describes how to build an application using a DBCP connection pool, MySQL Connector/J, and OceanBase Database to perform basic database operations, including creating tables, and inserting, deleting, updating, and querying data.
Prerequisites
You have registered an OceanBase Cloud account and created a cluster instance and an OceanBase Cloud MySQL-compatible tenant. For more information, see Create a cluster instance and Create a tenant.
You have obtained the connection string of the target MySQL-compatible tenant. For instructions, see Get a connection string.
You have installed JDK 1.8 and Maven.
You have installed Eclipse.
Note
The tool used to run the sample code in this topic is Eclipse IDE for Java Developers 2022-03. You can also choose a tool that suits your personal preference to run the sample code.
Procedure
Note
The procedure described in this topic is based on using Eclipse IDE for Java Developers 2022-03 in a Windows environment to compile and run the project. If you are using a different operating system or compiler, the steps may vary slightly.
Step 1: Import the dbcp-mysql-client project into Eclipse
Open Eclipse, and select File > Open Projects from File System from the menu bar.
In the dialog box that appears, click Directory, select the directory where the project is located, and then click Finish to complete the import.
Note
When importing a Maven project in Eclipse, it 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.
Step 2: Modify the database connection information in the dbcp-mysql-client project
Modify the database connection information in the dbcp-mysql-client/src/main/resources/db.properties file based on the connection string obtained in the prerequisites.
Example:
- The connection address is
t5******.********.oceanbase.cloud. - The access port is 3306.
- The name of the database to access is
test. - The tenant connection account is
test_user001. - The password is
******.
Code:
...
url=jdbc:mysql://t5******.********.oceanbase.cloud:3306/test
username=test_user001
password=******
...
Step 3: Run the dbcp-mysql-client project
In the project navigation view, locate and expand the src/main/java directory.
Right-click the Main.java file and select Run As > Java Application.
In the console window of Eclipse, view the project's log information and output results.
You can also execute the following SQL statement in OceanBase Client (OBClient) to view the results.
obclient [test]> SELECT * FROM test_tbl1;Example output:
+------+--------------+ | id | name | +------+--------------+ | 5 | test_update | | 6 | test_insert6 | | 7 | test_insert7 | | 8 | test_insert8 | | 9 | test_insert9 | +------+--------------+ 5 rows in set
Sample project overview
Click dbcp-mysql-client to download the project code, which is a compressed file named dbcp-mysql-client.zip.
After decompressing it, you will get a folder named dbcp-mysql-client. The directory structure is as follows:
dbcp-mysql-client
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── Main.java
│ └── resources
│ └── db.properties
└── pom.xml
File description:
src: The root directory for source code.main: The main code directory, containing the application's core logic.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, containing logic for creating tables, and inserting, deleting, updating, and querying data.resources: The resource file directory, containing configuration files.db.properties: The connection pool configuration file, containing relevant database connection parameters.pom.xml: The Maven project configuration file, used to manage project dependencies and build settings.
Introduction to pom.xml code
The pom.xml file is the configuration file for a Maven project, defining information such as 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 pom.xml file in this topic mainly includes the following parts:
File declaration statement.
Declares that this file is an XML file, using XML version
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure the POM 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,http://maven.apache.org/POM/4.0.0, and the location of its XSD file,http://maven.apache.org/xsd/maven-4.0.0.xsd. - Use the
<modelVersion>element to specify the POM model version used by this 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 asdbcp-mysql-client. - Use
<version>to specify the project version as1.0-SNAPSHOT.
Sample code:
<groupId>com.example</groupId> <artifactId>dbcp-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>- Use
Configure the properties of the project's source files.
Specifies the Maven compiler plugin as
maven-compiler-pluginand sets both the source and target Java versions to 8. This means the project's source code is written using Java 8 features, and the compiled bytecode will also be compatible with the Java 8 runtime environment. This configuration ensures 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 on which the project depends.
Define dependencies using
<dependency>:MySQL JDBC dependency:
- Use
<groupId>to specify the dependency's organization asmysql. - Use
<artifactId>to specify the dependency name asmysql-connector-java. - Use
<version>to specify the dependency version as5.1.47.
- Use
dbcp dependency:
- Use
<groupId>to specify the dependency's organization asorg.apache.commons. - Use
<artifactId>to specify the dependency name ascommons-dbcp2. - Use
<version>to specify the dependency version as2.9.0.
- Use
Sample code:
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.9.0</version> </dependency> </dependencies>
Introduction to the db.properties Code
db.properties is the connection pool configuration file used in this example, containing the configuration properties for the connection pool. These properties include the driver class name, database URL, username, password, connection pool size and limits, connection timeout, and options for handling abandoned connections.
The code in this db.properties file mainly consists of the following parts:
Configure database connection parameters.
- Set the driver class name, which is the class name for the MySQL JDBC driver:
com.mysql.jdbc.Driver. - Set the database connection URL, including the host IP, port number, and the database to be accessed.
- Set the database username.
- Set the database password.
- Set connection properties.
useSSL=falseindicates not to use SSL encryption for the connection, andcharacterEncoding=UTF-8indicates to use UTF-8 encoding for data transmission.
Code:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://$host:$port/$database_name username=$user_name password=$password connectionProperties=useSSL=false;characterEncoding=UTF-8Parameter explanation:
$host: Obtained from the-hparameter in the connection string, which is the connection address for OceanBase Cloud.$port: Obtained from the-Pparameter in the connection string, which is the connection port for OceanBase Cloud.$database_name: Obtained from the-Dparameter in the connection string, which is the name of the database to be accessed.$user_name: Obtained from the-uparameter in the connection string, which is the account name.$password: Obtained from the-pparameter in the connection string, which is the account password.
- Set the driver class name, which is the class name for the MySQL JDBC driver:
Configure other DBCP connection pool parameters.
Set the initial size of the connection pool to
30, which is the number of connections initially created in the pool.Set the maximum number of connections in the pool to
30, which is the maximum number of connections allowed in the pool.Set the maximum number of idle connections allowed in the pool to
10.Set the minimum number of idle connections to keep in the pool to
5. If the number of idle connections falls below this value, the pool creates new connections.Set the maximum wait time (in milliseconds) for obtaining a connection from the pool to
1000. If all connections in the pool are occupied and no connections are available, the operation will wait until a connection becomes available or the maximum wait time is exceeded.Set the timeout period (in seconds) before removing abandoned connections to
1.Note
The default value of `removeAbandonedTimeout` is 300 seconds. In this example, it is set to 1 second for testing purposes. You can adjust this value as needed to meet your application requirements.
Whether connections in the program are reclaimed by the pool after they are no longer in use:
- Set whether to detect and remove abandoned connections during maintenance. Set this to
true. - Set whether to detect and remove abandoned connections when borrowing a connection from the pool. Set this to
true.
- Set whether to detect and remove abandoned connections during maintenance. Set this to
Code:
initialSize=30 maxTotal=30 maxIdle=10 minIdle=5 maxWaitMillis=1000 removeAbandonedTimeout=1 removeAbandonedOnMaintenance=true removeAbandonedOnBorrow=true
Notice
The specific attribute (parameter) configuration depends on project requirements and database characteristics. We recommend that you adjust and configure them according to the actual situation. For more information about DBCP connection pool parameters, see BasicDataSource Configuration Parameters.
Basic data source configuration parameters for a DBCP connection pool:
Category |
Attribute |
Default value |
Description |
|---|---|---|---|
| Required parameters | driverClass | N/A | The class name of the database driver. |
| url | N/A | The URL used to connect to the database. | |
| username | N/A | The username used to connect to the database. | |
| password | N/A | The password used to connect to the database. | |
| Recommended parameters | initialSize | 0 | The initial size of the connection pool, which is the number of initial connections created when the connection pool starts. If set to a value greater than 0, the specified number of connections will be created during the connection pool initialization. This allows connections to be created in advance and reduces the latency when the client first requests a connection. |
| maxTotal | 8 | The maximum number of connections in the connection pool, which is the maximum number of connections allowed to exist in the connection pool. If set to a negative number, there is no limit. | |
| maxIdle | 8 | The maximum number of idle connections allowed to remain in the connection pool without releasing additional connections. If set to a negative number, there is no limit. | |
| minIdle | 0 | The minimum number of idle connections allowed to remain in the connection pool without releasing additional connections. If set to a negative number, there is no limit. | |
| maxWaitMillis | indefinitely | The maximum wait time (in milliseconds) for obtaining a connection from the connection pool. Setting it to -1 indicates infinite wait. If set to a positive number, the operation to wait for a connection will wait for the specified time when all connections in the connection pool are occupied. An exception will be thrown after the time expires. | |
| validationQuery | N/A | The SQL query statement used to validate whether a connection is valid. If specified, this query must be an SQL SELECT statement that returns at least one row. If not specified, the connection will be validated by calling the isValid() method. |
|
| testOnBorrow | true | Specifies whether to perform validation when borrowing an object from the connection pool. If an object cannot be validated, it will be removed from the connection pool and another object will be borrowed. | |
| testWhileIdle | false | Specifies whether the connection pool performs validation when idle. If set to true, the connection pool will periodically execute validation queries to check the validity of idle connections. If an object fails validation, it will be removed from the connection pool. |
|
| Optional parameters | connectionProperties | N/A | Specifies additional connection properties in key-value pairs. These properties are passed to the underlying JDBC driver when obtaining a database connection. The string format must be propertyName=property;
NoticeThe |
|
false | These two parameters control the removal behavior when a connection is considered abandoned.
true, the connection pool can automatically detect and remove abandoned connections. Abandoned connections are those that have not been used for a long time, possibly due to the application not closing the connection properly. By removing these abandoned connections, database resources can be released and the performance and efficiency of the connection pool can be improved. |
Introduction to Main.java
The Main.java file is part of a sample program that demonstrates obtaining a database connection through the DBCP connection pool and performing a series of database operations, including creating tables, inserting data, deleting data, updating data, querying data, and printing the query results.
The code in the Main.java file mainly consists of the following parts:
Import required classes and interfaces.
Import the necessary classes and interfaces for reading files, database operations, and the database connection pool. These classes and interfaces will be used in the subsequent code.
- Declare a package named
com.example, which will hold the current Java class. - Import the
java.io.FileInputStreamclass for reading files. - Import the
java.sql.Connectioninterface, representing a connection to the database. - Import the
java.sql.PreparedStatementinterface, representing a precompiled SQL statement. - Import the
java.sql.ResultSetinterface, representing the result set of a database query. - Import the
java.sql.SQLExceptionexception class, representing SQL operation exceptions. - Import the
java.util.Propertiesclass for loading configuration files. - Import the
org.apache.commons.dbcp2.BasicDataSourceclass, representing a database connection pool. - Import the
org.apache.commons.dbcp2.BasicDataSourceFactoryclass for creating a database connection pool.
Code:
package com.example; import java.io.FileInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.dbcp2.BasicDataSourceFactory;- Declare a package named
Define the class name and methods.
- Create the Main class and define a
mainmethod as the program's entry point. - In the
mainmethod, first call thecreateDataSource()method to create a connection pool objectdataSource. - Use a
try-with-resourcesstatement to automatically close resources when the lifecycle of the connection pool object ends. - In the
tryblock, call thegetConnection()method to obtain a database connection objectconnfrom the connection pool. - Call the
createTable(),insertData(),deleteData(),updateData(), andqueryData()methods in sequence to perform the corresponding database operations. - If an exception occurs, print the exception information in the
catchblock.
Code:
public class Main { public static void main(String[] args) { try (BasicDataSource dataSource = createDataSource()) { try (Connection conn = dataSource.getConnection()) { createTable(conn); insertData(conn); deleteData(conn); updateData(conn); queryData(conn); } } catch (Exception e) { e.printStackTrace(); } } // Create a connection pool // Define the method for creating a table. // Define the method for inserting data. // Define the method for deleting data. // Define the method for updating data. // Define the method for querying data. }- Create the Main class and define a
Create a connection pool.
Provide a convenient method for creating a database connection pool by initializing it with parameters read from a configuration file. The specific steps are as follows:
- Define a private static method
createDataSource()with a return type ofBasicDataSource. The method may throw anException. - Create a
Propertiesobjectpropsto store the database connection configuration information. - Create a
FileInputStreamobjectisto read thedb.propertiesfile located in thesrc/main/resourcesdirectory. - Use the
load()method to load the key-value pairs from thedb.propertiesfile into thepropsobject. - Call the
BasicDataSourceFactory.createDataSource(props)method, using thepropsobject as a parameter, to create and return aBasicDataSourceobject.
Code:
private static BasicDataSource createDataSource() throws Exception { Properties props = new Properties(); FileInputStream is = new FileInputStream("src/main/resources/db.properties"); props.load(is); return BasicDataSourceFactory.createDataSource(props); }- Define a private static method
Define a method for creating a table.
Provide a method to create a specified table in the database. It accepts a connection object as a parameter and uses prepared statements to execute the table creation SQL statement. The specific steps are as follows:
- Define a private static method
createTable()that accepts aConnectionobject as a parameter. The method may throw anSQLException. - Define a string variable
createTableSqlto store the SQL statement for creating the table. The SQL statement specifies the table name astest_tbl1and defines two columns: one namedidof typeINT, and another namednameof typeVARCHAR(32). - Use the
conn.prepareStatement(createTableSql)method to create aPreparedStatementobject namedcreateTableStmt, which is used to execute the precompiled SQL statement. - Call the
execute()method to execute the SQL statement for creating the table.
Sample code:
private static void createTable(Connection conn) throws SQLException { String createTableSql = "CREATE TABLE test_tbl1 (id INT, name VARCHAR(32))"; try (PreparedStatement createTableStmt = conn.prepareStatement(createTableSql)) { createTableStmt.execute(); } }- Define a private static method
Define a method for inserting data.
Provide a method to insert specified data into a table in the database. It accepts a connection object as a parameter and uses prepared statements to execute the data insertion SQL statement. The specific steps are as follows:
Define a private static method
insertData()that accepts aConnectionobject as a parameter. The method may throw anSQLException.Define a string variable
insertDataSqlto store the SQL statement for inserting data.Use the
conn.prepareStatement(insertDataSql)method to create aPreparedStatementobject namedinsertDataStmt, which is used to execute the precompiled SQL statement.Use a
forloop to insert data into the table:- Loop
10times, inserting one piece of data in each iteration. - Use the
setInt()method to set the value of the loop variableias the value for the first parameter in the SQL statement. - Use the
setString()method to set the stringtest_insert + ias the value for the second parameter in the SQL statement. - Call the
executeUpdate()method to execute the SQL statement for inserting data into the database.
- Loop
Sample code:
private static void insertData(Connection conn) throws SQLException { String insertDataSql = "INSERT INTO test_tbl1 (id, name) VALUES (?, ?)"; try (PreparedStatement insertDataStmt = conn.prepareStatement(insertDataSql)) { for (int i = 0; i < 10; i++) { insertDataStmt.setInt(1, i); insertDataStmt.setString(2, "test_insert" + i); insertDataStmt.executeUpdate(); } } }Define a method for deleting data.
Provide a method to delete data that meets specific conditions from the database. It accepts a connection object as a parameter and uses prepared statements to execute the data deletion SQL statement. The specific steps are as follows:
- Define a private static method
deleteData()that accepts aConnectionobject as a parameter. The method may throw anSQLException. - Define a string variable
deleteDataSqlto store the SQL statement for deleting data. - Use the
conn.prepareStatement(deleteDataSql)method to create aPreparedStatementobject nameddeleteDataStmt, which is used to execute the precompiled SQL statement. - Use the
setInt()method to set the number 5 as the parameter value in the SQL statement. - Call the
executeUpdate()method to execute the SQL statement for deleting data that meets the conditions from the database.
Sample code:
private static void deleteData(Connection conn) throws SQLException { String deleteDataSql = "DELETE FROM test_tbl1 WHERE id < ?"; try (PreparedStatement deleteDataStmt = conn.prepareStatement(deleteDataSql)) { deleteDataStmt.setInt(1, 5); deleteDataStmt.executeUpdate(); } }- Define a private static method
Define a method for updating data.
Provide a method to update data that meets specific conditions in the database. It accepts a connection object as a parameter and uses prepared statements to execute the data update SQL statement. The specific steps are as follows:
- Define a private static method named
updateData(), which takes aConnectionobject as a parameter and may throw anSQLException. - Define a string variable named
updateDataSqlto store the SQL statement for updating data. - Use the
conn.prepareStatement(updateDataSql)method to create aPreparedStatementobject namedupdateDataStmt. This object is used to execute precompiled SQL statements. - Use the
setString()method to set the stringtest_updateas the value of the first parameter in the SQL statement. - Use the
setInt()method to set the number5as the value of the second parameter in the SQL statement. - Call the
executeUpdate()method to execute the SQL statement, which updates data that meets the conditions in the database.
Sample code:
private static void updateData(Connection conn) throws SQLException { String updateDataSql = "UPDATE test_tbl1 SET name = ? WHERE id = ?"; try (PreparedStatement updateDataStmt = conn.prepareStatement(updateDataSql)) { updateDataStmt.setString(1, "test_update"); updateDataStmt.setInt(2, 5); updateDataStmt.executeUpdate(); } }- Define a private static method named
Define a method for querying data.
Provide a method to query data from the database and process it. It takes a connection object as a parameter and uses a prepared statement to execute the SQL query. The specific steps are as follows:
Define a private static method named
queryData(), which takes aConnectionobject as a parameter and may throw anSQLException.Define a string variable named
queryDataSqlto store the SQL statement for querying data.Use the
conn.prepareStatement(queryDataSql)method to create aPreparedStatementobject namedqueryDataStmt. This object is used to execute precompiled SQL statements.Execute the SQL query using the
queryDataStmt.executeQuery()method, and use theResultSetobjectrsto receive the query results.Use a
whileloop to traverse the query result set by calling thers.next()method:- Use the
getInt()method to get the integer value of the column namedidin the result set and assign it to the variableid. - Use the
getString()method to get the string value of the column namednamein the result set and assign it to the variablename. - Print the
idandnamefrom the query result.
- Use the
Sample code:
private static void queryData(Connection conn) throws SQLException { String queryDataSql = "SELECT * FROM test_tbl1"; try (PreparedStatement queryDataStmt = conn.prepareStatement(queryDataSql)) { try (ResultSet rs = queryDataStmt.executeQuery()) { while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("id: " + id + ", name: " + name); } } } }
Complete sample 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>dbcp-mysql-client</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
# Database Connect Information
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://$host:$port/$database_name
username=$user_name
password=$password
connectionProperties=useSSL=false;characterEncoding=UTF-8
# ConnectionPool Parameters
initialSize=30
maxTotal=30
maxIdle=10
minIdle=5
maxWaitMillis=1000
removeAbandonedTimeout=1
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
package com.example;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
public class Main {
public static void main(String[] args) {
try (BasicDataSource dataSource = createDataSource()) {
try (Connection conn = dataSource.getConnection()) {
createTable(conn);
insertData(conn);
deleteData(conn);
updateData(conn);
queryData(conn);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Create ConnectionPool
private static BasicDataSource createDataSource() throws Exception {
Properties props = new Properties();
FileInputStream is = new FileInputStream("src/main/resources/db.properties");
props.load(is);
return BasicDataSourceFactory.createDataSource(props);
}
// Create table
private static void createTable(Connection conn) throws SQLException {
String createTableSql = "CREATE TABLE test_tbl1 (id INT, name VARCHAR(32))";
try (PreparedStatement createTableStmt = conn.prepareStatement(createTableSql)) {
createTableStmt.execute();
}
}
// Insert data
private static void insertData(Connection conn) throws SQLException {
String insertDataSql = "INSERT INTO test_tbl1 (id, name) VALUES (?, ?)";
try (PreparedStatement insertDataStmt = conn.prepareStatement(insertDataSql)) {
for (int i = 0; i < 10; i++) {
insertDataStmt.setInt(1, i);
insertDataStmt.setString(2, "test_insert" + i);
insertDataStmt.executeUpdate();
}
}
}
// Delete data
private static void deleteData(Connection conn) throws SQLException {
String deleteDataSql = "DELETE FROM test_tbl1 WHERE id < ?";
try (PreparedStatement deleteDataStmt = conn.prepareStatement(deleteDataSql)) {
deleteDataStmt.setInt(1, 5);
deleteDataStmt.executeUpdate();
}
}
// Update data
private static void updateData(Connection conn) throws SQLException {
String updateDataSql = "UPDATE test_tbl1 SET name = ? WHERE id = ?";
try (PreparedStatement updateDataStmt = conn.prepareStatement(updateDataSql)) {
updateDataStmt.setString(1, "test_update");
updateDataStmt.setInt(2, 5);
updateDataStmt.executeUpdate();
}
}
// Query data
private static void queryData(Connection conn) throws SQLException {
String queryDataSql = "SELECT * FROM test_tbl1";
try (PreparedStatement queryDataStmt = conn.prepareStatement(queryDataSql)) {
try (ResultSet rs = queryDataStmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
}
}
}
}
References
For more information about MySQL Connector/J, see Overview of MySQL Connector/J.