golang连接clickhouse

2,666 阅读1分钟
  1. 连接数据库 全局一个数据库连接和上下文
package models

import (	
	"github.com/ClickHouse/clickhouse-go/v2"
	"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
)


var dbch driver.Conn
var ctxch context.Context

func initch() {
	dbch, err = clickhouse.Open(&clickhouse.Options{
		Addr: []string{127.0.0.1:9000},
		Auth: clickhouse.Auth{
			Database: database,
			Username: username,
			Password: password,
		},
		Settings: clickhouse.Settings{
			"max_execution_time": 60,
		},
		DialTimeout: 5 * time.Second,
		Compression: &clickhouse.Compression{
			Method: clickhouse.CompressionLZ4,
		},
		//Debug: true,
	})
	if err != nil {
		logs.SLogger.Infof(err.Error())
	}
	ctxch = clickhouse.Context(context.Background(), clickhouse.WithSettings(clickhouse.Settings{
		"max_block_size": 10,
	}))
}
  1. 查询数据库
sql := fmt.Sprintf("SELECT * FROM `replay_data_temporary` WHERE receive_time BETWEEN '%s' AND '%s' ORDER BY receive_time", sTime, eTime)
	logs.SLogger.Infof("数据库sql: %+v", sql)
	err := dbch.Select(ctxch, &ops, sql)