Updated on 2025-04-14 GMT+08:00

Establishing a Connection

This section describes the sample code for creating a ClickHouse connection.

The following code snippets are provided in the initConnection method of the ClickhouseJDBCHaDemo class. During connection creation, the user and password configured in Table 1 are used as authentication credentials. ClickHouse performs security authentication on the server with the user and password.

For versions earlier than MRS 3.3.0, the following is an example of a generation fragment:

clickHouseProperties.setPassword(userPass);
clickHouseProperties.setUser(userName);
BalancedClickhouseDataSource balancedClickhouseDataSource = new BalancedClickhouseDataSource(JDBC_PREFIX + UriList, clickHouseProperties);

For MRS 3.3.0 and later versions, the following is an example of a generation fragment:

clickHouseProperties.setProperty(ClickHouseDefaults.USER.getKey(), userName);
clickHouseProperties.setProperty(ClickHouseDefaults.PASSWORD.getKey(), userPass);
try {
    clickHouseProperties.setProperty(ClickHouseClientOption.FAILOVER.getKey(), "21");
    clickHouseProperties.setProperty(ClickHouseClientOption.LOAD_BALANCING_POLICY.getKey(), "roundRobin");
    balancedClickhouseDataSource = new ClickHouseDataSource(JDBC_PREFIX + UriList, clickHouseProperties);
} catch (Exception e) {
    LOG.error("Failed to create balancedClickHouseProperties.");
    throw e;
}