This topic describes how to use OceanBase Connector/J and OceanBase Database to build an application that performs basic operations such as creating tables, inserting data, and querying data.
To download the project code, click java-oceanbase-jdbc.
Prerequisites
You have installed OceanBase Database.
You have installed JDK 1.8 and Maven.
You have installed Eclipse.
Note
This topic uses Eclipse IDE for Java Developers 2022-03 to run the sample code. You can also choose a suitable tool as needed.
Procedure
Note
The procedures provided in this topic are for compiling and running the project using Eclipse IDE for Java Developers 2022-03 under the Windows environment. If you are using a different operating system environment or compiler, the procedures may be slightly different.
- Obtain the URL of OceanBase Database.
- Obtain the code of the
java-oceanbase-jdbcproject. - Import the
java-oceanbase-jdbcproject to Eclipse. - Modify the database connection information in the
java-oceanbase-jdbcproject. - Run the
java-oceanbase-jdbcproject.
Step 1: Obtain the URL of OceanBase Database
Contact the OceanBase Database deployment personnel or administrator to obtain the database connection string.
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 corresponding information of the URL below based on the OceanBase Database connection string.
The URL used to connect to OceanBase Database in Oracle mode is similar to the following example:
jdbc:oceanbase://host:port/schema_name?user=$user_name&password=$passwordParameters:
host: the IP address for connecting to OceanBase Database. For connection through an OceanBase Database Proxy (ODP), this parameter is the IP address of the ODP. For direct connection, this parameter is 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.schema_name: the name of the schema to be accessed.user_name: the tenant account. For connection through ODP, two account formats are supported:Username@Tenant name#Cluster nameandCluster name:Tenant name:Username. For direct connection, theUsername@Tenant nameformat is supported.password: the account password.
For more information about URL parameters, see Database URL.
Step 2: Obtain the code of the java-oceanbase-jdbc project
Click java-oceanbase-jdbc to download the project code, which is a compressed package named java-oceanbase-jdbc.zip.
Decompress the package to obtain the folder named java-oceanbase-jdbc. The directory is structured as follows:
.
|-- README-CN.md
|-- README.md
|-- pom.xml
|-- run.sh
`-- src
`-- main
`-- java
`-- com
`-- oceanbase
`-- example
|-- InsertAndSelectExample.java
`-- OceanBaseClientTest.java
File and directory description:
README-CN.md: This file is the documentation of the project, mainly for Chinese users.README.md: This file is also the documentation of the project, but it is written in English, mainly for English users.pom.xml: This file is the configuration file of the Maven project and defines the dependencies, plug-ins, and build rules of the project.run.sh: This file is a shell script for automatically compiling and running Java applications.src: This directory contains the source code and resource files of the project and is the main directory of the project.main: This directory contains main Java source code of the project.java: This directory is the root directory of Java source code.com: This directory is the root directory of Java packages.oceanbase: This directory is a sub-directory undercom, indicating that the project is related to OceanBase Database.example: This directory is a sub-directory underoceanbase, indicating that this project is a sample program for demonstrating how to connect to and operate OceanBase Database by using the OceanBase JDBC driver.InsertAndSelectExample.java: This file is a part of the sample program and contains a sample classInsertAndSelectExamplefor demonstrating how to insert and query data.OceanBaseClientTest.java: This file is a part of the sample program and contains a sample classOceanBaseClientTestfor demonstrating how to connect to a database, execute SQL statements, and query data.
Code in the pom.xml file
The pom.xml file is the configuration file of the Maven project and defines the dependencies, plug-ins, and build rules of the project. Maven is a Java project management tool that can automatically download dependencies and compile and package projects.
Code in the pom.xml file contains the following parts:
Declare the file.
Declare that this file is an XML file, using XML version
1.0, and the character encoding isUTF-8.The code is as follows:
<?xml version="1.0" encoding="UTF-8"?>Configure namespaces and the POM model version.
xmlns: the default XML namespace, which is set tohttp://maven.apache.org/POM/4.0.0.xmlns:xsi: the XML namespace for XML elements prefixed withxsi, which is set tohttp://www.w3.org/2001/XMLSchema-instance.xsi:schemaLocation: the location of an XML schema definition (XSD) file. The value consists of two parts: the default XML namespace (http://maven.apache.org/POM/4.0.0) and the URI of the XSD file (http://maven.apache.org/xsd/maven-4.0.0.xsd).<modelVersion>: the POM model version used by the POM file, which is set to4.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 project information.
<groupId>: the ID of the project group, which is set tocom.oceanbase.example.<artifactId>: the ID of the project, which is set tooceanbase-client.<version>: the project version, which is set to1.0-SNAPSHOT.<name>: the project name, which is set toob-example-oceanbase-client.
The code is as follows:
<groupId>com.oceanbase.example</groupId> <artifactId>oceanbase-client</artifactId> <version>1.0-SNAPSHOT</version> <name>ob-example-oceanbase-client</name>Define source file properties of the project by using
<properties>.<project.build.sourceEncoding>: the encoding used by the project source file, which is set toUTF-8.<maven.compiler.source>: the version of the Java source code used by the Maven compiler, which is set to1.8.<maven.compiler.target>: the version of the Java bytecode generated by the Maven compiler, which is set to1.8.<exec.mainClass>: specifies to execute the sample programcom.oceanbase.example.InsertAndSelectExamplein the project.
The 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>Define the components on which the project depends by using
<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.
<dependency>: defines a dependency.<groupId>: the ID of the group to which the dependency belongs, which is set tocom.oceanbase.<artifactId>: the ID of the dependency, which is set tooceanbase-client.<version>: the version of the dependency, which is set to2.4.2.
The code is as follows:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency> </dependencies>
Code in the InsertAndSelectExample.java file
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.
Code in the InsertAndSelectExample.java file contains the following parts:
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 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 name 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 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. In the URL:
jdbc:oceanbase: specifies to use the OceanBase JDBC driver to connect to the database.host:port: the IP address and port number of OceanBase Database.opt1=val1&opt2=val2...: additional connection properties, or URL parameters.schema_name: the name of the schema to be accessed.String user = "user_name": the username required for logging on to the database.String password = "******": 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 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 thenameandagecolumns. If the table already exists, drop the existing one and then create a new one. Perform the following steps:- 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 thenameandagecolumns. The data type of thenamecolumn isvarchar(50), and that of theagecolumn isint.
The 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. Perform the following steps:- 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 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 data records.
Query all data from the
persontable, and return the results to the console. Perform the following steps:- 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 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 code is as follows:
ps.close(); stmt.close(); conn.close();
Complete code for your reference
<?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();
}
}
Step 3: Import the java-oceanbase-jdbc project into Eclipse
Open Eclipse and select the Import option from the File menu.

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

On the next page that appears, click the Browse button, 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. The icon of Package Explorer is 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 use Eclipse to import a Maven project, 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.

Step 4: 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 1: Obtain the URL of OceanBase Database.
For example:
- The IP address of the OBServer node is
10.10.10.1. - The access port is 2881.
- The name of the schema to be accessed is
sys. - The connection account of the tenant is
sys@oracle001. Here,oracle001is a user tenant created in the Oracle mode of 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?socketTimeout=7200000&useUnicode=true&characterEncoding=UTF-8&useCursorFetch=true&defaultFetchSize=100&useSSL=false&rewriteBatchedStatements=true&cachePrepStmts=true&useServerPrepStmts=true&usePieceData=true&allowSendParamTypes=true";
String user = "root@oracle001";
String password = "******";
Step 5: Run the java-oceanbase-jdbc project
View the project structure in Package Explorer.

Right-click the main class in the project and choose Run As > Run Configurations... to open the Run Configurations page.

On the Run Configurations page, choose Java Application > New_configuration, and select the
com.oceanbase.example.InsertAndSelectExampleproject for Main class.
View the logs and output of the project in the Eclipse console.

References
For more information about OceanBase Connector/J, see OceanBase Connector/J.