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)
}
}
- Install the driver by running
go get github.com/ClickHouse/clickhouse-go/v2/lib/driver. - Import the driver with a blank identifier to register it with
database/sql. - Call
sql.Open("clickhouse", "clickhouse://user:password@host:port/database")to create the connection. - Call
db.Ping()to verify the connection is active before querying.