2

I want to Scan a sql.Row into a slice like so:

func printRows(rows *sql.Rows){
    defer rows.Close()

    for rows.Next() {
        var row = []interface{}{}
        err := rows.Scan(row...)
        if err != nil {
            log.Fatal(err)
        }
        r, err := json.Marshal(row)
        if err != nil {
            log.Fatal(err)
        }
        log.Println("row:", r);
    }
}

but I am getting this error:

2020/02/23 20:05:14 raw query: SELECT * FROM user_table LIMIT 500 2020/02/23 20:05:14 sql: expected 6 destination arguments in Scan, not 0

anyone know how to make this generic without using a slice?

  • Why are you trying to avoid using a slice? You can check how many columns are returned (```len(rows.Columns())```) and then that to build your slice. [This post](http://go-database-sql.org/varcols.html) has more info. – Brits Feb 24 '20 at 04:36
  • if it's that simple can you just add an answer here? thx –  Feb 24 '20 at 05:05
  • Possible duplicate of [1](https://stackoverflow.com/questions/23507531/is-golangs-sql-package-incapable-of-ad-hoc-exploratory-queries), [2](https://stackoverflow.com/questions/29102725/go-sql-driver-get-interface-column-values), [3](https://stackoverflow.com/questions/53435455/handling-dynamic-queries-cant-scan-into-struct), [4](https://stackoverflow.com/questions/14477941/read-select-columns-into-string-in-go), ... – Charlie Tumahai Feb 24 '20 at 05:18

1 Answers1

2

You can do it this way:

cols, err := rows.Columns() // Remember to check err afterwards
vals := make([]interface{}, len(cols))
for i, _ := range cols {
    vals[i] = new(string)
}

for rows.Next() {
    err = rows.Scan(vals...)
}

on the internet they say you can use:

    vals[i] = new(sql.RawBytes)

instead of

    vals[i] = new(string)

but I think (string) is fine, idk