在Go中,如何将数据库行转换为结构体? [英] How do I convert a database row into a struct, in Go?

查看:704
本文介绍了在Go中,如何将数据库行转换为结构体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类型User struct {
名称字符串
Id int
Score int
}

和一个具有相同模式的数据库表。将数据库行解析为结构最简单的方法是什么?我已经在下面添加了一个答案,但我不确定它是最好的答案。 解决方案

只需在 Scan 函数中手动分配所有结构值。

  func getUser(name string)(* User,error){
var u User
//这会调用sql.Open等
db:= getConnection()
//注意以下语法仅适用于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
}
}


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.

解决方案

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

这篇关于在Go中,如何将数据库行转换为结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆