本文介绍如何在 Go 开发环境连接并访问 ByteHouse 云数仓。
ByteHouse 兼容下列开源 ClickHouse Go Driver 程序:
本章节介绍通过 ClickHouse/clickhouse-go 程序连接 ByteHouse 的基本用法,您可以在程序Github 主页 获取最新的文档和发布版本信息。
注意
go get -u github.com/ClickHouse/clickhouse-go/v2
安装完成后,在 go 程序代码的 import 中插入以下内容。
import ( "github.com/ClickHouse/clickhouse-go/v2" )
可参考下面代码样例,注意根据 前提条件中获取的信息填写连接信息中的{HOST:PORT}
、{API_KEY}
等字段。
conn, err := clickhouse.Open(&clickhouse.Options{ Addr: []string{"<<Host:Port>>"}, // Use {HOST:PORT} //Addr: []string{"gateway.aws-us-east-1.bytehouse.cloud:19000"}, Auth: clickhouse.Auth{ Database: "", // Set default datebase Username: "bytehouse", Password: "<<YOUR_API_KEY>>", // Use {API_KEY} },
package test import ( "context" "crypto/tls" "fmt" "net" "testing" "time" "github.com/ClickHouse/clickhouse-go/v2" ) func TestConnection(t *testing.T) { conn, err := clickhouse.Open(&clickhouse.Options{ //Addr: []string{"gateway.aws-us-east-1.bytehouse.cloud:19000"}, Auth: clickhouse.Auth{ Database: "", Username: "bytehouse", Password: "<<YOUR_API_KEY>>", }, TLS: &tls.Config{ InsecureSkipVerify: false, }, DialContext: func(ctx context.Context, addr string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, "tcp", addr) }, Debug: true, Debugf: func(format string, v ...any) { fmt.Printf(format, v) }, Settings: clickhouse.Settings{ "max_execution_time": 60, }, Compression: &clickhouse.Compression{ Method: clickhouse.CompressionLZ4, }, DialTimeout: time.Second * 30, MaxOpenConns: 5, MaxIdleConns: 5, ConnMaxLifetime: time.Duration(10) * time.Minute, ConnOpenStrategy: clickhouse.ConnOpenInOrder, BlockBufferSize: 10, MaxCompressionBuffer: 10240, ClientInfo: clickhouse.ClientInfo{ // optional, please see Client info section in the README.md Products: []struct { Name string Version string }{ {Name: "my-app", Version: "0.1"}, }, }, TLS: &tls.Config{}, }) if err != nil { t.Fatal(err) } if err := conn.Ping(context.Background()); err != nil { t.Fatal(err) } rows, err := conn.Query(context.Background(), "show databases") if err != nil { t.Fatal(err) } type db struct { Name string CreatedAt int64 CreatedBy string UpdatedAt int64 UpdatedBy string LastQueriedAt int64 LastQueriedBy string Comments string Engine string } d := &db{} for rows.Next() { if err := rows.ScanStruct(d); err != nil { t.Fatal(err) } fmt.Println(d) } }