Updated on 2025-07-25 GMT+08:00

Using JDBC to Connect to Doris Clusters in Non-SSL Mode

When code retry and load balancing are performed at the application layer, multiple Doris FE node addresses need to be configured for an application. For example, if a connection exits abnormally, the system automatically retries on another connection.

JDBC Connector

If the MySQL JDBC Connector is used to connect to Doris, the automatic retry mechanism of JDBC can be used.

 private static String URL = "jdbc:mysql:loadbalance://" +
        "[FE1_host]:[FE1_port],[FE2_host]:[FE2_port],[FE3_host]:[FE3_port]/demo?" +
        "loadBalanceConnectionGroup=first&ha.enableJMX=true";

Sample code:

public class Test {
    private static String URL = "jdbc:mysql:loadbalance://" +
        "FE1:9030,FE2:9030,FE3:9030/demo?" +
        "loadBalanceConnectionGroup=first&ha.enableJMX=true";
    static Connection getNewConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        // There will be security risks if the password used for authentication is directly written into code. Encrypt the password in the configuration file or environment variables for storage;
       // In this example, the password is stored in environment variables for identity authentication. Before running the code in this example, configure environment variables first.
        String password = System.getenv("USER_PASSWORD");
        return DriverManager.getConnection(URL, "admin", password);
    }
    public static void main(String[] args) throws Exception {
        Connection c = getNewConnection();
        while (true) {
            try {
                String query = "your sqlString";
                c.setAutoCommit(false);
                Statement s = c.createStatement();
                ResultSet resultSet = s.executeQuery(query);
                System.out.println("begin print");
                while(resultSet.next()) {
                    int id = resultSet.getInt(1);
                    System.out.println("id is: "+id);
                }
                System.out.println("end print");
                Thread.sleep(Math.round(100 * Math.random()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}