Mark Harrison
Mark Harrison

Reputation: 304662

In Go sqlx, how can I fetch all rows in a slice of slices (not maps)?

This is not a duplicate of Create a Map in Golang from database Rows. That question is about reading rows as maps; this question is about reading rows as slices. A map will not work as order needs to be preserved.

How can I use sqlx to get a slice of slices that represents all rows and columns in a query? Not a slice of maps, but a slice of slices, similar to what Python's cursor.fetchall() returns.

I am currently doing this:

var results []interface{}
for rows.Next() {
    cols, err := rows.SliceScan()
    checkErr(err)
    results = append(results, cols)
}

I see this example in the documentation:

var names []string
err = db.Select(&names, "SELECT name FROM place LIMIT 10")

which returns a slice of strings.

How can I combine these to to receive a slice of slices, something like this (non-working) example?

results := make([][]interface{}, 0)
err := db.Select(&results, "select * from foo")
// panic: non-struct dest type slice with >1 columns (5)

Upvotes: 0

Views: 430

Answers (0)

Related Questions