How do I convert a database row into a struct

后端 未结 7 921
谎友^
谎友^ 2020-12-07 14:07

Let\'s say I have a struct:

type User struct {
    Name  string
    Id    int
    Score int
}

And a database table with the same schema. Wh

相关标签:
7条回答
  • 2020-12-07 14:56

    Here's one way to do it - just assign all of the struct values manually in the Scan function.

    func getUser(name string) (*User, error) {
        var u User
        // this calls sql.Open, etc.
        db := getConnection()
        // note the below syntax only works for postgres
        err := db.QueryRow("SELECT * FROM users WHERE name = $1", name).Scan(&u.Id, &u.Name, &u.Score)
        if err != nil {
            return &User{}, err
        } else {
            return &u, nil
        }
    }
    
    0 讨论(0)
提交回复
热议问题