Home > Enterprise >  Go SQL, scanning a row as a slice?
Go SQL, scanning a row as a slice?

Time:08-13

closing note: This question does not ask "how can I find the number of columns returned?" which is len(row.Columns()). It is asking a Go-related question concerning the rows.Scan() function.

How can I extract all the columns in a row into a slice or equivalent? For example

    rows, err := db.Query("select * from foo")
    for rows.Next() {
        fmt.Printf("% v\n", rows)

I would like to extract the data in lastcols as a slice.

&{dc:0xc000486000 releaseConn:0x5e20c0 rowsi:0xc0000cf180 cancel:<nil>
closeStmt:<nil> closemu:{w:{state:0 sema:0} writerSem:0
readerSem:0 readerCount:0 readerWait:0} closed:false lasterr:<nil>
lastcols:[abc 123 foo {wall:0 ext:0 loc:0xc0000ec000}]}

context:

  • for debugging, I would like to select * from sometable and display the results without knowing the table format in advance.
  • github.com/lib/pg SQL driver.

CodePudding user response:

You can find the Columns with rows.Columns() then you can make a slice to fetch the data.

columns, err := rows.Columns()
if err != nil {
    return err
}

values := make([]interface{}, len(columns))
for i := range values {
    values[i] = new(interface{})
}

err = rows.Scan(values...)
if err != nil {
    return err
}
  • Related