HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How do I convert a database row into a struct

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
databaserowhowstructconvertinto

Problem

Let's say I have a struct:

type User struct {
    Name  string
    Id    int
    Score int
}


And a database table with the same schema. What's the easiest way to parse a database row into a struct? I've added an answer below but I'm not sure it's the best one.

Solution

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
    }
}

Code Snippets

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
    }
}

Context

Stack Overflow Q#17265463, score: 46

Revisions (0)

No revisions yet.