简体   繁体   中英

Scan row into slice

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?

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 inte.net they say you can use:

    vals[i] = new(sql.RawBytes)

instead of

    vals[i] = new(string)

but I think (string) is fine, idk

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