不使用Scan函数从数据库查询中返回结果 – Golang

huangapple go评论78阅读模式
英文:

Returning results form a database query without using Scan - Golang

问题

根据我所了解,在Go语言中从数据库中获取数据的一般方式是像这里描述的那样:http://go-database-sql.org/retrieving.html

大致上可以这样做:

rows, err := db.Query("select id, name from users where id = ?", 1)
if err != nil {
    log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
    err := rows.Scan(&id, &name)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(id, name)
}

然而,如果我想为数据库访问创建一个包装器,我将无法在其中使用Scan,并且我也不想返回rows来处理。除了Scan之外,是否有任何方法可以获取从rows返回的对象?它们可能都是interface{}类型,但这完全可以接受。如果我遍历rows,是否有办法访问对象,以便我可以将其转换为给定的结构体或其他类型?

英文:

From what I can gather, in Go the way to fetch data from a database is generally something like described here: http://go-database-sql.org/retrieving.html

Doing something along the lines of :

rows, err := db.Query("select id, name from users where id = ?", 1)
if err != nil {
	log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
	err := rows.Scan(&id, &name)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(id, name)
}

If i wanted to create a wrapper for database access though I wouldnt be able to do the Scan in there and i would rather not return the rows to do that with. Is there any way to get the objects returned from the rows other than Scan? They would all be interface{}'s probably but thats totally fine. Failing that, if I iterate through the rows is there a way to get access ot the object so I could cast to a given struct or anything?

答案1

得分: 1

> 除了Scan之外,有没有其他方法可以获取从行返回的对象?

没有。

> 如果我遍历行,有没有办法访问对象,以便我可以将其转换为给定的结构或其他内容?

没有,不像你想象的那样(例如,Go中没有类型转换)。

将它们扫描到适合你需求的任何类型中,从interface{}sql.RawBytes或实现Scanner接口的其他类型。请参考database/sql包的文档,特别是database/sql.Rows.Scan (https://pkg.go.dev/database/sql#Rows.Scan)。大多数情况下,查看文档会更快。

英文:

> Is there any way to get the objects returned from the rows other than Scan?

No.

> if I iterate through the rows is there a way to get access ot the object so I could cast to a given struct or anything?

No, not in they way you imagine (e.g. there are no casts in Go).

Scan them into whatever fits your needs, from interface{} to sql.RawBytes or smth implementing Scanner. Please consult the documentation of package database/sql, especially database/sql.Rows.Scan (https://pkg.go.dev/database/sql#Rows.Scan) . Most of the time it's quicker to look at the documentation.

huangapple
  • 本文由 发表于 2022年6月29日 01:06:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/72790597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定