How do I convert a database row into a struct

后端 未结 7 932
谎友^
谎友^ 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条回答
  •  旧时难觅i
    2020-12-07 14:49

    use : go-models-mysql sqlbuilder

    val, err = m.ScanRowType(row, (*UserTb)(nil))
    

    or the full code

    import (
        "database/sql"
        "fmt"
    
        lib "github.com/eehsiao/go-models-lib"
        mysql "github.com/eehsiao/go-models-mysql"
    )
    
    // MyUserDao : extend from mysql.Dao
    type MyUserDao struct {
        *mysql.Dao
    }
    
    // UserTb : sql table struct that to store into mysql
    type UserTb struct {
        Name       sql.NullString `TbField:"Name"`
        Id         int            `TbField:"Id"`
        Score      int            `TbField:"Score"`
    }
    
    // GetFirstUser : this is a data logical function, you can write more logical in there
    // sample data logical function to get the first user
    func (m *MyUserDao) GetFirstUser() (user *User, err error) {
    
        m.Select("Name", "Id", "Score").From("user").Limit(1)
        fmt.Println("GetFirstUser", m.BuildSelectSQL().BuildedSQL())
        var (
            val interface{}
            row *sql.Row
        )
    
        if row, err = m.GetRow(); err == nil {
            if val, err = m.ScanRowType(row, (*UserTb)(nil)); err == nil {
                u, _ := val.(*UserTb)
    
                user = &User{
                    Name:       lib.Iif(u.Name.Valid, u.Nae.String, "").(string),
                    Id:         u.Id,
                    Score:      u.Score,
                }
            }
        }
        row, val = nil, nil
    
        return
    }
    

提交回复
热议问题