How do I convert a database row into a struct

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

    I recommend github.com/jmoiron/sqlx.

    From the README:

    sqlx is a library which provides a set of extensions on go's standard database/sql library. The sqlx versions of sql.DB, sql.TX, sql.Stmt, et al. all leave the underlying interfaces untouched, so that their interfaces are a superset on the standard ones. This makes it relatively painless to integrate existing codebases using database/sql with sqlx.

    Major additional concepts are:

    • Marshal rows into structs (with embedded struct support), maps, and slices
    • Named parameter support including prepared statements
    • Get and Select to go quickly from query to struct/slice

    The README also includes a code snippet demonstrating scanning a row into a struct:

    type Place struct {
        Country       string
        City          sql.NullString
        TelephoneCode int `db:"telcode"`
    }
    // Loop through rows using only one struct
    place := Place{}
    rows, err := db.Queryx("SELECT * FROM place")
    for rows.Next() {
        err := rows.StructScan(&place)
        if err != nil {
            log.Fatalln(err)
        } 
        fmt.Printf("%#v\n", place)
    }
    

    Note that we didn't have to manually map each column to a field of the struct. sqlx has some default mappings for struct fields to database columns, as well as being able to specify database columns using tags (note the TelephoneCode field of the Place struct above). You can read more about that in the documentation.

提交回复
热议问题