将数据库列扫描到带有切片的结构体中

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

Scan database columns into struct with slices

问题

我有一个包含切片字段的结构体,现在我想将 SQL 查询的列收集到这些切片中。

type StructOfSlices struct {
    Column1 []string
    Column2 []string
}

有没有比下面更简单/更可扩展/更高效的方法呢?

首先,我创建一个"单个"版本的结构体...

type StructSingle struct {
    Column1 string
    Column2 string
}

var s StructOfSlices

rows, _ := db.Query("SELECT column1, column2 FROM table")

然后逐个扫描每个单个的结构体...

for rows.Next() {
    var single StructSingle

    db.Scan(&single.Column1, &single.Column2)

    s.Column1 = append(s.Column1, single.Column1)
    s.Column2 = append(s.Column2, single.Column2)
}

最后将其追加到切片结构体中。

英文:

I have a struct with fields containing slices like so, and now I want to collect the columns from a sql-query into these slices

type StructOfSlices struct {
    Column1 []string
    Column2 []string
}

Is there an easier/more scalable/efficient way to do it than the below?

Here I first create a "single" version of the struct...

type StructSingle struct {
    Column1 string
    Column2 string
}

var s StructOfSlices

rows, _ := db.Query("SELECT column1, column2 FROM table")

...and then scan each individual single struct...

for rows.Next() {
    var single StructSingle

    db.Scan(&single.Column1, &single.Column2)

    s.Column1 = append(s.Column1, single.Column1)
    s.Column2 = append(s.Column2, single.Column2)
}

...and then append to the slice struct

答案1

得分: 5

不,那就是正确的方法。你基本上是在进行数据透视,我不知道有什么自动完成的方法。考虑到你只用了几行代码就完成了,我认为你的解决方案没有问题。

由于你是按列扫描到一个变量中,实际上你根本不需要StructSingle类型 - 你可以只使用两个本地的string变量,这样会更简单:

for rows.Next() {
    var col1, col2 string
    db.Scan(&col1, &col2)

    s.Column1 = append(s.Column1, col1)
    s.Column2 = append(s.Column2, col2)
}

然后完全去掉StructSingle类型。

英文:

No, that's the way to do it. You're basically doing a pivot, there's no way I know of to do that automagically. Given that you've done it in just a couple of lines of code, I don't see a problem with your solution.

Since you're scanning into a variable per column, you don't actually need the StructSingle type at all - you could just use two local string variables, which would make it even simpler:

for rows.Next() {
	var col1, col2 string
    db.Scan(&col1, &col2)

    s.Column1 = append(s.Column1, col1)
    s.Column2 = append(s.Column2, col2)
}

And get rid of the StructSingle type entirely.

huangapple
  • 本文由 发表于 2017年7月20日 21:34:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/45216349.html
匿名

发表评论

匿名网友

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

确定