How to Connect to ClickHouse from Go

Connect to ClickHouse from Go by installing the clickhouse-go driver and using sql.Open with the clickhouse:// DSN scheme.

Use the official clickhouse-go driver with the database/sql package to connect to ClickHouse from Go. Add the driver to your module, import it, and call sql.Open with the DSN string containing your connection details.

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

func main() {
	db, err := sql.Open("clickhouse", "clickhouse://user:password@localhost:9000/default")
	if err != nil {
		panic(err)
	}
	defer db.Close()
	// Verify connection
	if err := db.Ping(); err != nil {
		panic(err)
	}
}
  1. Install the driver by running go get github.com/ClickHouse/clickhouse-go/v2/lib/driver.
  2. Import the driver with a blank identifier to register it with database/sql.
  3. Call sql.Open("clickhouse", "clickhouse://user:password@host:port/database") to create the connection.
  4. Call db.Ping() to verify the connection is active before querying.