OceanBase Database supports connections through the official MySQL JDBC driver.
Prerequisites
- The Java version on your computer is Java JDK 8 or later.
- MySQL Connector/J has been installed, and the runtime environment has been configured.
For the download and installation methods, see Connector/J Downloads and Connector/J Installation.
Procedure
The following is an example of connecting a Java application to OceanBase Database in Linux.
Run the following sample code to verify the database connection. If the message true is returned, the database connection is successful.
Note:
If your MySQL Connector/J version is 5.x, replace com.mysql.cj.jdbc.Driver with com.mysql.jdbc.Driver in Class.forName("com.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.cj.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();
//Perform operations such as deleting tables, creating new tables, and inserting 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();
}
}
}
Parameter description
connection = DriverManager.getConnection("jdbc:mysql://{hostname}:{port}/{dbname}?user={username}&password={password}")
- hostname: IP address to connect to OceanBase Database, usually the OBProxy address.
- port: Port to connect to OceanBase Database, also the listening port of OBProxy. The default port is 2883, which can be customized.
- dbname: Name of the database to be accessed.
- username: The tenant's connection account, and the tenant's administrator username is
rootby default. - password: Account password.
Example: jdbc:mysql://172.30.xx.xx:2883/test?user=r***&password=***1**