1.创建clickhouse环境#
安装clickhouse
或者使用docker
参考:https://hub.docker.com/r/clickhouse/clickhouse-server
1 | docker run -d -p 18123:8123 -p 19000:9000 --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server:23.8 |
使用datagrip连接
创建表和测试数据
1 | CREATE TABLE default.my_first_table |
2.使用client连接clickhouse#
golang客户端连接clickhouse,可以使用 clickhouse-go 这个库
引入依赖
1 | go get github.com/ClickHouse/clickhouse-go |
导入clickhouse的driver和database/sql,也可以使用github.com/jmoiron/sqlx,参考:golang操作clickhouse使用入门
1 | import "database/sql" |
否则会报
1 | sql: unknown driver "clickhouse" (forgotten import?) |
创建连接
1 | source := "tcp://localhost:19000?username=default&password=&database=default&block_size=4096" |
记得添加defer用于关闭连接
创建clickhouse表
1 | query := ` |
插入数据
1 | var arr [][]any |
查询数据
1 | // 读取数据 |
输出
1 | [{101 Hello, ClickHouse! 2024-05-25 15:54:00 +0000 UTC -1} {101 Granules are the smallest chunks of data read 2024-05-25 15:54:00 +0000 UTC 3.14159} {102 Insert a lot of rows per batch 2024-05-25 15:54:00 +0000 UTC 1.41421} {102 Sort your data based on your commonly-used queries 2024-05-25 15:54:00 +0000 UTC 2.718}] |