You can connect to OceanBase Database by using MySQL Connector/J, which is the official Java Database Connectivity (JDBC) driver for MySQL.
Prerequisites
You have installed or upgraded to JDK 8 or later on your computer.
You have installed MySQL Connector/J and configured its runtime environment.
We recommend that you use MySQL Connector/J 5.1.47. For more information about the download and installation methods, see Connector/J Downloads and Connector/J Installation.
Connect to OceanBase Database
The following example shows how to connect to a database by using MySQL Connector/J 5.1.47 in Linux.
After you install MySQL Connector/J 5.1.47 and configure its runtime environment, you can connect to the database based on the following sample code, which uses the Test.java file as an example:
Notice
If you use MySQL Connector/J 8.x, replace
com.mysql.jdbc.Driverin theClass.forName("com.mysql.jdbc.Driver")field withcom.mysql.cj.jdbc.Driver.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
try{
Connection connection = DriverManager.getConnection("jdbc:mysql://172.30.xx.xx:2883/test?user=r***&password=");
System.out.println(connection.getAutoCommit());
Statement sm = connection.createStatement();
//Drop or create a table, and insert data.
String q1="drop table if exists t_meta_form";
sm.executeUpdate(q1);
String q2="CREATE TABLE t_meta_form ( name varchar(36) NOT NULL DEFAULT ' ', id int NOT NULL ) DEFAULT CHARSET = utf8mb4";
String q3="insert into t_meta_form (name,id) values ('an','1')";
sm.executeUpdate(q2);
sm.executeUpdate(q3);
}catch(SQLException se){
System.out.println("error!");
se.printStackTrace() ;
}
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
Parameters
connection = DriverManager.getConnection("jdbc:mysql://{hostname}:{port}/{dbname}?user={username}&password={password}")
hostname: the IP address for connecting to OceanBase Database, which is usually the IP address of an OBProxy.
port: the port for connecting to OceanBase Database, which is also the listening port of the OBProxy. Default value: 2883, which can be customized.
dbname: the name of the database to be connected.
username: the connection account of the tenant. By default, the username of the tenant administrator is
root.password: the password of the connection account.
Example: jdbc:mysql://172.30.xx.xx:2883/test?user=r***&password=******
After you edit the code, run the following command to compile and execute the file. If true is returned, the database is connected.
//Specify the actual installation path of mysql-connector-java-5.1.47.jar.
export CLASSPATH=/usr/share/java/mysql-connector-java-5.1.47.jar:$CLASSPATH
//Compile the file.
javac Test.java
//Run the file.
java Test