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?
Advertisement
Answer
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