All Products
Search
Document Center

:Connect Java applications to OceanBase Database

Last Updated:Jan 13, 2023

You can use OceanBase Connector/J to create connections between Java-based applications and OceanBase Database. This topic describes the prerequisites and connection procedure.

Prerequisites

  • A basic database development environment is deployed.

  • You have installed or upgraded to JDK 8 on your computer.

  • You have obtained the installation package of the OceanBase Connector/J driver from OceanBase Technical Support.

Procedure

Place the JAR installation package of OceanBase Connector/J in the local directory by using cmd and perform the following connection test:

  1. Compile the Java file HelloWorld.java and load OceanBase Connector/J.

    public class HelloWorld {
       public static void main(String[] args) {
           try {
               Class.forName("com.oceanbase.jdbc.Driver");
           } catch (ClassNotFoundException e) {
               e.printStackTrace();
           }
       }
    }
  2. Run the following command to compile the Java sample file:

    javac -cp target/oceanbase-client-{version}.jar HelloWorld.java
    Note

    You can change the compilation path as needed.

  3. Run the following command to run the Java sample file:

    java -cp .:target/oceanbase-client-{version}.jar HelloWorld

If all the preceding steps are performed and no error is returned, the JAR package of the OceanBase Connector/J driver is correctly loaded.

After OceanBase Connector/J is loaded, connect to OceanBase Database based on the IP address and port. Enter the actual IP address, port number, and schema name in the String url field in the following code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class HelloWorld {
   public static void main(String[] args) {
       try {
           String url = "jdbc:oceanbase://ipaddress:port/shemaname?pool=false";
           String  user = "username";
           String  password = "password";
           Class.forName("com.oceanbase.jdbc.Driver");
           Connection connection = DriverManager.getConnection(url, user, password);
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
   }

After the connection to OceanBase Database is established, repeat steps 2 and 3 to load classes.

For more information about how to use OceanBase Connector/J, see OceanBase Connector/J Developer Guide.