简体   繁体   中英

How initialize the result of groupArray function of the ClickHouse to the array

In my Go application, I make a request to the ClickHouse database via clickhouse-go package. This query which I make return always only one record and it's an array of integers. Is there any way to initialize that result to the array in Go?

var ids []int

ids, err := database.ClickHouse.Exec("SELECT groupArray(ID) FROM layers;")
if err != nil {
    fmt.Println(err)
}

I tried such code but it raises an error: cannot assign Result to ids (type []int) in multiple assignment.

The Exec method doesn't return the rows, it returns driver.Result and error .

func (stmt *stmt) Exec(args []driver.Value) (driver.Result, error)
                                             ^^^^^^^^^^^^^

And, the driver.Result type has the following definition (comments removed):

type Result interface {
    LastInsertId() (int64, error)
    RowsAffected() (int64, error)
}

What you're looking for is Query method that returns driver.Rows :

func (stmt *stmt) Query(args []driver.Value) (driver.Rows, error)
                                              ^^^^^^^^^^^

You can then iterate over the rows to generate the array you want.

An example has been listed in the README.md (copied here):

rows, err := connect.Query("SELECT country_code, os_id, browser_id, categories, action_day, action_time FROM example")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

for rows.Next() {
    var (
        country               string
        os, browser           uint8
        categories            []int16
        actionDay, actionTime time.Time
    )
    if err := rows.Scan(&country, &os, &browser, &categories, &actionDay, &actionTime); err != nil {
        log.Fatal(err)
    }
    log.Printf("country: %s, os: %d, browser: %d, categories: %v, action_day: %s, action_time: %s", country, os, browser, categories, actionDay, actionTime)
}

Hope that helps!

var ids []int64

err := database.ClickHouse.QueryRow("SELECT groupArray(ID) FROM layers").Scan(&ids)
if err != nil {
    fmt.Println(err)
}
fmt.Println(ids)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM