Back to integrations

Go

core

Installation

go get github.com/ClickHouse/clickhouse-go/v2

Examples

Client API

Connect (native protocol)
conn, err := clickhouse.Open(&clickhouse.Options{
	Addr: []string{"<host>:9440"},
	Auth: clickhouse.Auth{
		Database: "default",
		Username: "default",
		Password: "<password>",
	},
	TLS: &tls.Config{},
})
Connect (HTTP protocol)
conn, err := clickhouse.Open(&clickhouse.Options{
	Addr: []string{"<host>:8443"},
	Auth: clickhouse.Auth{
		Database: "default",
		Username: "default",
		Password: "<password>",
	},
	TLS: &tls.Config{},
    Protocol: clickhouse.HTTP,
})
Create a table
err := conn.Exec(context.Background(), `
    CREATE TABLE IF NOT EXISTS my_table (Col1 UInt8, Col2 String)
`)
if err != nil {
    return err
}
Batch insert
batch, err := conn.PrepareBatch(ctx, "INSERT INTO my_table")
if err != nil {
    return err
}

if err := batch.Append(uint8(42), "ClickHouse")); err != nil {
    return err
}
if err := batch.Send(); err != nil {
    return err
}
Querying rows
rows, err := conn.Query(ctx, "SELECT Col1, Col2 FROM my_table")
if err != nil {
    return err
}
for rows.Next() {
    var (
        col1 uint8
        col2 string
    )
    if err := rows.Scan(&col1, &col2); err != nil {
        return err
    }
    fmt.Printf("row: col1=%d, col2=%s\n", col1, col2)
}
rows.Close()
return rows.Err()

database/sql driver

Connect (native protocol)
conn, err := sql.Open("clickhouse", "clickhouse://<host>:9440?username=default&password=<password>/<database>")
Connect (HTTP protocol)
conn, err := sql.Open("clickhouse", "http://<host>:8443?username=default&password=<password>/<database>")
Create a table
err := conn.ExecContext(context.Background(), `
    CREATE TABLE IF NOT EXISTS my_table (Col1 UInt8, Col2 String)
`)
if err != nil {
    return err
}
Batch insert
stmt, err := conn.PrepareContext(ctx, "INSERT INTO my_table")
if err != nil {
    return err
}

if err := stmt.Exec(uint8(42), "ClickHouse")); err != nil {
    return err
}
if err := stmt.Commit(); err != nil {
    return err
}
Querying rows
rows, err := conn.QueryContext(ctx, "SELECT Col1, Col2 FROM my_table")
if err != nil {
    return err
}
for rows.Next() {
    var (
        col1 uint8
        col2 string
    )
    if err := rows.Scan(&col1, &col2); err != nil {
        return err
    }
    fmt.Printf("row: col1=%d, col2=%s\n", col1, col2)
}
rows.Close()
return rows.Err()

Other integrations

Get started with ClickHouse Cloud for free

We'll get you started on a 30 day trial and $300 credits to spend at your own pace.