如何将数据库行转换为结构 [英] How do I convert a database row into 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.
推荐答案
这是一种方法-只需在Scan
函数中手动分配所有结构值即可.
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
}
}
这篇关于如何将数据库行转换为结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文