How do I convert a database row into a struct

后端 未结 7 923
谎友^
谎友^ 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:46

    Here is a library just for that: scany.

    You can use it like that:

    type User struct {
        Name  string
        Id    int
        Score int
    }
    
    // db is your *sql.DB instance
    // ctx is your current context.Context instance
    
    // Use sqlscan.Select to query multiple records.
    var users []*User
    sqlscan.Select(ctx, db, &users, `SELECT name, id, score FROM users`)
    
    // Use sqlscan.Get to query exactly one record.
    var user User
    sqlscan.Get(ctx, db, &user, `SELECT name, id, score FROM users WHERE id=123`)
    

    It's well documented and easy to work with.

    Disclaimer: I am the author of this library.

提交回复
热议问题