大数据ClickHouse(十七):Java 读写ClickHouse API

2022-09-02 00:09:27 浏览数 (1)

​Java 读写ClickHouse API

Java读取ClickHouse中的数据API 。

一、首先需要加入maven依赖

代码语言:javascript复制
<!-- 连接ClickHouse需要驱动包-->
<dependency>
  <groupId>ru.yandex.clickhouse</groupId>
  <artifactId>clickhouse-jdbc</artifactId>
  <version>0.2.4</version>
</dependency>

二、Java 读取ClickHouse单节点表数据

代码语言:javascript复制
ClickHouseProperties props = new ClickHouseProperties();
props.setUser("default");
props.setPassword("");
BalancedClickhouseDataSource dataSource = new BalancedClickhouseDataSource("jdbc:clickhouse://node1:8123/default", props);
ClickHouseConnection conn = dataSource.getConnection();
ClickHouseStatement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select id,name,age from test");
while(rs.next()){
    int id = rs.getInt("id");
    String name = rs.getString("name");
    int age = rs.getInt("age");
    System.out.println("id = " id ",name = " name  ",age = " age);
}

三、Java 读取ClickHouse集群表数据

代码语言:javascript复制
ClickHouseProperties props = new ClickHouseProperties();
props.setUser("default");
props.setPassword("");
BalancedClickhouseDataSource dataSource = new BalancedClickhouseDataSource("jdbc:clickhouse://node1:8123,node2:8123,node3:8123/default", props);
ClickHouseConnection conn = dataSource.getConnection();
ClickHouseStatement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select id,name from t_cluster");
while(rs.next()){
    int id = rs.getInt("id");
    String name = rs.getString("name");
    System.out.println("id = " id ",name = " name );
}

四、Java向ClickHouse 表中写入数据

代码语言:javascript复制
// API 操作:
ClickHouseProperties props = new ClickHouseProperties();
props.setUser("default");
props.setPassword("");
BalancedClickhouseDataSource dataSource = new BalancedClickhouseDataSource("jdbc:clickhouse://node1:8123/default", props);
ClickHouseConnection conn = dataSource.getConnection();
ClickHouseStatement statement = conn.createStatement();
statement.execute("insert into test values (100,'王五',30)");//可以拼接批量插入多条

代码语言:javascript复制
查询default库下 test表 数据:
node1 :) select * from test;
┌──id─┬─name─┬─age─┐
│ 100 │ 王五 │  30 │
└─────┴──────┴─────┘
┌─id─┬─name─┬─age─┐
│  1 │ 张三 │  18 │
│  2 │ 李四 │  19 │
└────┴──────┴─────┘

0 人点赞