1

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.
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
  • Does this answer your question? [Find the number of columns in a table](https://stackoverflow.com/questions/658395/find-the-number-of-columns-in-a-table) – Luuk Aug 12 '22 at 19:04
  • Does this answer your question? [How can i get a count(\*) of all the columns in a table? Using PostgreSql](https://stackoverflow.com/questions/53087945/how-can-i-get-a-count-of-all-the-columns-in-a-table-using-postgresql) – nbk Aug 12 '22 at 19:09
  • 1
    This is from memory and I'm on my phone and can't verify: Use [rows.Columns](https://pkg.go.dev/database/sql#Rows.Columns) (or ColumnTypes) to determine how many columns there are. make a []interface{} with the same length. Scan into the slice: `rows.Scan(mySlice...)`. You may have to create (pointers to) values with concrete types at each slice index before scanning (based on info returned by rows.ColumnTypes). – Peter Aug 12 '22 at 20:08
  • @Luuk It is a Go-related API question, not how to find the number of columns. – Mark Harrison Aug 12 '22 at 21:41
  • @nbk This is not a Postgresql question, it is a Go API question. – Mark Harrison Aug 12 '22 at 21:41
  • @MarkHarrison Does it matter where you get the information from? – nbk Aug 12 '22 at 21:43
  • @nbk I added the information that I'm using the postgresql driver in case it was useful in answering the question. The actual number of columns returned is len(rows.Columns()). – Mark Harrison Aug 12 '22 at 21:55
  • Answer to [this question](https://stackoverflow.com/q/17845619/11810946) and [this question](https://stackoverflow.com/q/51731423/11810946) provide options (these are go specific and address the use of `rows.Scan()` :-) ). – Brits Aug 12 '22 at 22:12

1 Answers1

2

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
}
Fenistil
  • 3,734
  • 1
  • 27
  • 31