user2433953
user2433953

Reputation: 131

How to assign a set of rows(Retrieved from a database) in an array of structure in GoLang?

I am trying to retrieve a set of rows from postgresql and trying to assign it in an array of structure. My code goes like this :

var test []Demo
    err := sqlx.Get(db,&test, `
                    select *
                    from demo
                    where id = $1`,
                    5,
            )
            if err != nil {
                    fmt.Println("Error",err)
                    fmt.Println("DatabaseExtraction Error")
                    return nil, errors.Wrap(err, "select error")
            } else {
                    fmt.Println("No Extraction Error")
            }

I have a structure like this :

type Demo struct {
        ID         int64         `db:"id"`
        Name       string        `db:"name"`
}

But I am getting an error like this Error scannable dest type slice with >1 columns (2) in result (code: 2) Also I don't get any error if I replace var test []Demo with var test Demo.

Upvotes: 0

Views: 910

Answers (1)

Kugel
Kugel

Reputation: 838

If you call Get it expects only one row to be returned. If you want to select multiple rows, use Select and pass a pointer to your slice. For example:

var rows []Demo
err := sqlx.Select(&rows, `SELECT * FROM "demo"`)
// ...

Upvotes: 2

Related Questions