This topic introduces how to build an application by using OceanBase Connector/J and OceanBase Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, and data query.
Prerequisites
You have installed OceanBase Database.
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), but you can also choose a tool that suits your personal preference to run the 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
java-oceanbase-jdbcproject into Eclipse. - Obtain the URL of OceanBase Database.
- Modify the database connection information in the
java-oceanbase-jdbcproject. - Run the
java-oceanbase-jdbcproject.
Step 1: Import the java-oceanbase-jdbc project into Eclipse
Start Eclipse and choose File > Import....

In the Import window, choose Maven > Existing Maven Projects and click Next.

On the page that appears, click Browse, select the root directory of the Maven project, and then click Finish.

Eclipse automatically recognizes the
pom.xmlfile in the project and displays all Maven projects in Package Explorer. You can see the icon of Package Explorer displayed in the left-side panel of Eclipse. If the icon is not displayed, select the Window menu and choose Show View > Package Explorer.Note
When you import a Maven project using Eclipse, 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.
View the project.

Step 2: Obtain the URL of OceanBase Database
Contact the deployment personnel or administrator of OceanBase Database to obtain the database connection string.
Here is an example:
obclient -hxxx.xxx.xxx.xxx -P2883 -usys@oracel001#cluster_name -p******For more information about connection strings, see Connect to an OceanBase Database tenant by using OBClient.
Fill in the URL below based on the OceanBase Database connection string.
The following example shows how to connect to the Oracle mode of OceanBase Database by using the URL:
jdbc:oceanbase://$host:$port/$schema_name?user=$user_name&password=$passwordwhere
$hostspecifies the IP address for connecting to OceanBase Database. For connection through OceanBase Database Proxy (ODP), this parameter is the IP address of an ODP. For direct connection, this parameter is the IP address of an OBServer node.$portspecifies 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.$schema_namespecifies the name of the schema to access.$user_namespecifies 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.$passwordspecifies the account password.
For more information about URL parameters in OceanBase Connector/J, see Database URL.
Step 3: Modify the database connection information in the java-oceanbase-jdbc project
Modify the database connection information in the InsertAndSelectExample.java 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
10.10.10.1. - The port is
2881. - The name of the schema to be accessed is
sys. - The tenant account is
sys@oracle001, whereoracle001is an Oracle user tenant created in OceanBase Database, andsysis the username of theoracle001tenant. - The password is
******.
The sample code is as follows:
String url = "jdbc:oceanbase://10.10.10.1:2881/sys";
String user = "root@oracle001";
String password = "******";
Step 4: Run the java-oceanbase-jdbc project
View the project structure in Package Explorer.

Right-click the
mainclass and choose Run As > Run Configurations... to open the Run Configurations page.
On the Run Configurations page, choose Java Application > New_configuration and select
com.oceanbase.example.InsertAndSelectExamplefor Main class.
View the logs and output of the project in the Eclipse console.

Project code introduction
Click java-oceanbase-jdbc to download the project code, which is a compressed file named java-oceanbase-jdbc.zip.
After decompressing it, you will find a folder named java-oceanbase-jdbc. The directory structure is as follows:
.
|-- README-CN.md
|-- README.md
|-- pom.xml
|-- run.sh
`-- src
`-- main
`-- java
`-- com
`-- oceanbase
`-- example
|-- InsertAndSelectExample.java
`-- OceanBaseClientTest.java
Here is a breakdown of the files and directories:
README-CN.md: the project's documentation, mainly for Chinese users.README.md: the project's documentation written in English, mainly for English users.pom.xml: the configuration file for the Maven project, defining the project's dependencies, plugins, and build rules.run.sh: a shell script used primarily for automatically compiling and running Java applications.src: the directory for storing the project's source code and resource files. It is the main directory of the project.main: a Java source code directory for storing the main code of the project.java: the root directory for storing the Java source code.com: the root directory for storing the Java package.oceanbase: a sub-package under thecompackage, indicating that the project is related to OceanBase Database.example: a sub-package under theoceanbasepackage, indicating that the project is a sample program used to demonstrate how to use the OceanBase JDBC driver to connect to and operate OceanBase Database.InsertAndSelectExample.java: part of the sample program and contains a sample classInsertAndSelectExampleused to demonstrate how to insert and query data.OceanBaseClientTest.java: part of the sample program and contains a sample classOceanBaseClientTestused to demonstrate how to connect to the database, execute SQL statements, and perform data queries.
Code in pom.xml
The pom.xml file is a configuration file for Maven projects, which defines the dependencies, plug-ins, and build rules of the projects. Maven is a Java project management tool that can automatically download dependencies, compile, and package the projects.
To configure the pom.xml file, perform the following steps:
Declare the file.
Declare the file to be an XML file that uses XML standard
1.0and character encodingUTF-8.The sample code is as follows:
<?xml version="1.0" encoding="UTF-8"?>Configure the namespaces and the POM model version.
- Use
xmlnsto specifyhttp://maven.apache.org/POM/4.0.0as the default XML namespace for the POM. - Use
xmlns:xsito specifyhttp://www.w3.org/2001/XMLSchema-instanceas the XML namespace for xsi-prefixed elements. - Use
xsi:schemaLocationto provide a mapping from the default XML namespace for the POM (http://maven.apache.org/POM/4.0.0) to the location of the POM's XML schema definition (XSD) file (http://maven.apache.org/xsd/maven-4.0.0.xsd). - Use
<modelVersion>to specify4.0.0as the model version used by the POM.
The sample 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>- Use
Configure basic project information.
- Use
<groupId>to specifycom.oceanbase.exampleas the ID of the project group. - Use
<artifactId>to specifyoceanbase-clientas the ID of project. - Use
<version>to specify1.0-SNAPSHOTas the project version. - Use
<name>to specifyob-example-oceanbase-clientas the project name.
The sample code is as follows:
<groupId>com.oceanbase.example</groupId> <artifactId>oceanbase-client</artifactId> <version>1.0-SNAPSHOT</version> <name>ob-example-oceanbase-client</name>- Use
Define source file properties of the project in
<properties>.- Use
<project.build.sourceEncoding>to specifyUTF-8as the encoding method used by the project source file. - Use
<maven.compiler.source>to specify1.8as the version of the Java source code used by the Maven compiler. - Use
<maven.compiler.target>to specify1.8as the version of the Java bytecode generated by the Maven compiler. - Use
<exec.mainClass>to specify to execute the sample programcom.oceanbase.example.InsertAndSelectExamplein the project.
The sample code is as follows:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <exec.mainClass>com.oceanbase.example.InsertAndSelectExample</exec.mainClass> </properties>- Use
Configure project dependencies in
<dependencies>.Note
The following code defines that the project depends on OceanBase Connector/J V2.4.2. For more information about other versions, see OceanBase Connector/J.
- Use
<dependency>to define a dependency. - Use
<groupId>to specifycom.oceanbaseas the ID of the group that the dependency belongs to. - Use
<artifactId>to specifyoceanbase-clientas the dependency ID. - Use
<version>to specify2.4.2as the dependency version.
The sample code is as follows:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency> </dependencies>- Use
Code in InsertAndSelectExample.java
The InsertAndSelectExample.java file is a part of the sample program and contains a sample class InsertAndSelectExample for demonstrating how to insert and query data.
To configure the InsertAndSelectExample.java file, perform the following steps:
Define the package and import
java.sqlinterfaces and classes.Declare the name of the parent package of the file to be
com.oceanbase.example.Import the following interfaces and classes from the
java.sqlpackage:Connectioninterface: indicates a connection to a database.DriverManagerclass: provides a set of static methods for managing registration of the JDBC driver and obtaining a database connection. The most common method isgetConnection(), which is used to create a connection to a database.PreparedStatementinterface: indicates a precompiled SQL statement.ResultSetinterface: indicates a query result set.SQLExceptionclass: indicates exceptions that may occur when you use JDBC to connect to a database, such as connection failure and SQL statement execution failure.Statementinterface: indicates a statement in a database.
The sample code is as follows:
package com.oceanbase.example; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;Define the class and
mainmethod.Set the class name to
InsertAndSelectExample. The name must be the same as the file name.Set the
mainmethod topublic static void, a public static method that accepts a string arrayargsas parameters.throws ClassNotFoundException, SQLExceptionis used to declare that theClassNotFoundExceptionandSQLExceptionexceptions can be thrown from the method. The caller of the method that throws exceptions is required to handle the exceptions.The sample code is as follows:
public class InsertAndSelectExample { public static void main(String[] args) throws ClassNotFoundException, SQLException { // to do: // 3.connect to your database // 4.create a table // 5.insert records // 6.fetch all records // 7.release all resources } }Connect to a database and obtain the database connection object.
Define the URL with additional connection properties required for connecting to OceanBase Database, where
jdbc:oceanbasespecifies to use the OceanBase Connector/J driver to connect to the database.host:portspecifies the IP address and port number of OceanBase Database.opt1=val1&opt2=val2...indicates additional connection properties, or URL parameters. For more information about the additional connection properties of a URL, see Database URL.schema_namespecifies the name of the schema to access.String user = "user_name"specifies the username required for logging on to the database.String password = "******"specifies the password required for logging on to the database.
Obtain the database connection object as follows:
- Load the driver class named
com.oceanbase.jdbc.Driverby calling theforNamemethod ofClass. - Obtain the
Connectionobject namedconnby calling thegetConnectionmethod of theDriverManagerclass.
The sample code is as follows:
String url = "jdbc:oceanbase://host:port/schema_name?[opt1=val1&opt2=val2...]"; String user = "user_name"; String password = "******"; Class.forName("com.oceanbase.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, user, password);Create a table.
Create a table named
personwith thenameandagefields. If the table already exists, drop the existing one and then create a new one. The steps are as follows:- Create a
Statementobject namedstmtto send SQL statements to the database. - Call the
executemethod of thestmtobject to execute the SQL statementdrop table personto drop a table namedperson. Whether thepersontable already exists cannot be determined. Therefore, thetry-catchstructure is used to capture exceptions, to avoid a program crash caused by an attempt to drop a nonexistent table. - Call the
executemethod of thestmtobject again to execute the SQL statementcreate table person (name varchar(50), age int)to create a table namedpersonwith thenameandagefields. The data type of thenamefield isvarchar(50), and that of theagefield isint.
The sample code is as follows:
Statement stmt = conn.createStatement(); try {stmt.execute("drop table person");} catch (Exception ignore) {} stmt.execute("create table person (name varchar(50), age int)");- Create a
Insert data into the table.
Call the
PreparedStatementinterface to insert two data records into thepersontable in the database. The steps are as follows:- Create a
PreparedStatementobject namedpsto execute an SQL statement. The SQL statement isinsert into person values(?, ?)where?is a placeholder that indicates a value to be inserted. - Call the
setString()method to set the first placeholder toAdam. - Call the
setInt()method to set the second placeholder to28. - Execute an update to insert the first data record into the table.
- Call the
setString()method again to set the first placeholder toEve. - Call the
setInt()method again to set the second placeholder to26. - Execute an update again to insert the second data record into the table.
The sample code is as follows:
PreparedStatement ps = conn.prepareStatement("insert into person values(?, ?)"); ps.setString(1, "Adam"); ps.setInt(2, 28); ps.executeUpdate(); ps.setString(1, "Eve"); ps.setInt(2, 26); ps.executeUpdate();- Create a
Obtain all records.
Query all data from the
persontable, and return the results to the console. The steps are as follows:- Create a
PreparedStatementobject namedpsto execute an SQL statement. The SQL statement isselect * from person, which indicates to query all data from thepersontable. Call thesetFetchDirection()method to set the cursor in the result set to move forward, and call thesetConcurrency()method to set the result set to be read-only. - Perform a query operation, save the query results to the
ResultSetobject, and name theResultSetobjectrs. - Use the
whileloop to traverse theResultSetobject, and call thers.next()method to move the cursor to the next row of data.trueis returned if there is more data. In the loop, call thers.getString(1)method to obtain the values of the first column (namely, thenamecolumn in thepersontable), call thers.getInt(2)method to obtain the values of the second column (namely, theagecolumn), and return the values to the console in the format ofname is age years old. - After the loop ends, close the
ResultSetandPreparedStatementobjects.
The sample code is as follows:
ps = conn.prepareStatement("select * from person", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = ps.executeQuery(); while (rs.next()) { System.out.println(rs.getString(1) + " is " + rs.getInt(2) + " years old."); }- Create a
Release database resources.
Close the
PreparedStatement,Statement, andConnectionobjects to release database resources. This avoids resource consumption and performance issues.The sample code is as follows:
ps.close(); stmt.close(); conn.close();
Complete code examples
<?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.example</groupId>
<artifactId>oceanbase-client</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ob-example-oceanbase-client</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<exec.mainClass>com.oceanbase.example.InsertAndSelectExample</exec.mainClass>
</properties>
<dependencies>
<dependency>
<groupId>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
</project>
package com.oceanbase.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertAndSelectExample {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:oceanbase://host:port/schema_name?[opt1=val1&opt2=val2...]";
String user = "user_name";
String password = "******";
Class.forName("com.oceanbase.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
try {
stmt.execute("drop table person");
} catch (Exception ignore) {
}
stmt.execute("create table person (name varchar2(50), age int)");
PreparedStatement ps = conn.prepareStatement("insert into person values(?, ?)");
ps.setString(1, "Adam");
ps.setInt(2, 28);
ps.executeUpdate();
ps.setString(1, "Eve");
ps.setInt(2, 26);
ps.executeUpdate();
ps = conn.prepareStatement("select * from person", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + " is " + rs.getInt(2) + " years old.");
}
ps.close();
stmt.close();
conn.close();
}
}
References
For more information about OceanBase Connector/J, see OceanBase Connector/J.
Download the java-oceanbase-jdbc sample project