英文:
Use one struct for multiple SQL queries
问题
我有多个类似的SQL查询需要在Go代码中运行。像这样的:
type S1 struct {
X int
Y int
Z string
}
rows, err := db.Queryx("SELECT X,Y,Z FROM SomeTable")
for rows.Next() {
var p S1
err = rows.StructScan(&p)
}
type S2 struct {
Y int
Z string
}
rows, err := db.Queryx("SELECT Y,Z FROM SomeTable")
for rows.Next() {
var p S2
err = rows.StructScan(&p)
}
type S3 struct {
X int
Y int
}
rows, err := db.Queryx("SELECT X,Y FROM SomeTable")
for rows.Next() {
var p S3
err = rows.StructScan(&p)
}
有没有办法在这3个查询中使用一个结构体?理想情况下,希望能使用S1
结构体来处理这3个查询。可能很重要的一点是,使用的是Clickhouse数据库。SqlX文档并没有说明这是否可能,所以我想自己尝试弄清楚...
英文:
I have multiple similar SQL queries that I need to run in Go code.<br/>
Something like this:<br/>
type S1 struct {
X int
Y int
Z string
}
rows, err := db.Queryx("SELECT X,Y,Z FROM SomeTable")
for rows.Next() {
var p S1
err = rows.StructScan(&p)
}
type S2 struct {
Y int
Z string
}
rows, err := db.Queryx("SELECT Y,Z FROM SomeTable")
for rows.Next() {
var p S2
err = rows.StructScan(&p)
}
type S3 struct {
X int
Y int
}
rows, err := db.Queryx("SELECT X,Y FROM SomeTable")
for rows.Next() {
var p S3
err = rows.StructScan(&p)
}
Is there a way to use one struct for all 3 queries? <br/>
Ideally S1
being used for all 3 queries would be great.<br/>
Maybe it is important, Clickhouse database is being used.<br/>
SqlX documentation does not imply this is possible, hence the question while I try to figure it out on my own...
答案1
得分: 1
从这里获取答案:https://go.dev/doc/database/querying#multiple_rows
使用Scan方法,您可以为查询结果的每个查询列分配一个变量。
注意:未由scan()填充的值将默认为字段类型的零值。
type S1 struct {
X int
Y int
Z string
}
func run() {
rows, err := db.Queryx("SELECT X,Y,Z FROM SomeTable")
for rows.Next() {
var p S1
err = rows.Scan(&p.X, &p.Y, &p.Z)
}
rows, err := db.Queryx("SELECT Y,Z FROM SomeTable")
for rows.Next() {
var p S1
err = rows.Scan(&p.Y, &p.Z)
}
rows, err := db.Queryx("SELECT X,Y FROM SomeTable")
for rows.Next() {
var p S1
err = rows.Scan(&p.X, &p.Y)
}
}
英文:
Answer taken from here: https://go.dev/doc/database/querying#multiple_rows
Using the Scan method you can assign populate one variable for every query Column of the query result.
Note: the values not populated by scan(), will default to the zero value of the field type.
type S1 struct {
X int
Y int
Z string
}
func run() {
rows, err := db.Queryx("SELECT X,Y,Z FROM SomeTable")
for rows.Next() {
var p S1
err = rows.Scan(&S1.X, &S1.Y, &S1.Z)
}
rows, err := db.Queryx("SELECT Y,Z FROM SomeTable")
for rows.Next() {
var p S1
err = rows.Scan(&S1.Y, &S1.Z)
}
rows, err := db.Queryx("SELECT X,Y FROM SomeTable")
for rows.Next() {
var p S1
err = rows.Scan(&S1.X, &S1.Y)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论