How do I convert a database row into a struct

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

    Go package tests often provide clues as to ways of doing things. For example, from database/sql/sql_test.go,

    func TestQuery(t *testing.T) {
        /* . . . */
        rows, err := db.Query("SELECT|people|age,name|")
        if err != nil {
                t.Fatalf("Query: %v", err)
        }
        type row struct {
                age  int
                name string
        }
        got := []row{}
        for rows.Next() {
                var r row
                err = rows.Scan(&r.age, &r.name)
                if err != nil {
                        t.Fatalf("Scan: %v", err)
                }
                got = append(got, r)
        }
        /* . . . */
    }
    
    func TestQueryRow(t *testing.T) {
        /* . . . */
        var name string
        var age int
        var birthday time.Time
        err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age)
        /* . . . */
    }
    

    Which, for your question, querying a row into a structure, would translate to something like:

    var row struct {
        age  int
        name string
    }
    err = db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&row.age, &row.name)
    

    I know that looks similar to your solution, but it's important to show how to find a solution.

提交回复
热议问题