Go SQL, scanning a row as a slice?

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

Go SQL, scanning a row as a slice?

问题

结束语:
这个问题并没有问“如何找到返回的列数?”,即len(row.Columns())。它是一个关于rows.Scan()函数的Go相关问题。

我该如何将一行中的所有列提取到一个切片或等效的结构中?例如:

    rows, err := db.Query("select * from foo")
    for rows.Next() {
        fmt.Printf("%+v\n", rows)

我想将lastcols中的数据提取为一个切片。

&{dc:0xc000486000 releaseConn:0x5e20c0 rowsi:0xc0000cf180 cancel:<nil>
closeStmt:<nil> closemu:{w:{state:0 sema:0} writerSem:0
readerSem:0 readerCount:0 readerWait:0} closed:false lasterr:<nil>
lastcols:[abc 123 foo {wall:0 ext:0 loc:0xc0000ec000}]}

上下文:

  • 为了调试,我想执行select * from sometable并显示结果,而不需要提前知道表的格式。
  • 使用github.com/lib/pg SQL驱动程序。
英文:

closing note:
This question does not ask "how can I find the number of columns returned?" which is len(row.Columns()). It is asking a Go-related question concerning the rows.Scan() function.

How can I extract all the columns in a row into a slice or equivalent? For example

    rows, err := db.Query("select * from foo")
    for rows.Next() {
        fmt.Printf("%+v\n", rows)

I would like to extract the data in lastcols as a slice.

&{dc:0xc000486000 releaseConn:0x5e20c0 rowsi:0xc0000cf180 cancel:<nil>
closeStmt:<nil> closemu:{w:{state:0 sema:0} writerSem:0
readerSem:0 readerCount:0 readerWait:0} closed:false lasterr:<nil>
lastcols:[abc 123 foo {wall:0 ext:0 loc:0xc0000ec000}]}

context:

  • for debugging, I would like to select * from sometable and display the results without knowing the table format in advance.
  • github.com/lib/pg SQL driver.

答案1

得分: 2

你可以使用rows.Columns()来找到列,然后可以创建一个切片来获取数据。

columns, err := rows.Columns()
if err != nil {
    return err
}

values := make([]interface{}, len(columns))
for i := range values {
    values[i] = new(interface{})
}

err = rows.Scan(values...)
if err != nil {
    return err
}

请注意,这是一段Go代码,用于从数据库中获取数据。rows.Columns()函数用于获取查询结果的列名,然后使用rows.Scan()函数将查询结果的值存储到values切片中。

英文:

You can find the Columns with rows.Columns() then you can make a slice to fetch the data.

columns, err := rows.Columns()
if err != nil {
	return err
}

values := make([]interface{}, len(columns))
for i := range values {
	values[i] = new(interface{})
}

err = rows.Scan(values...)
if err != nil {
	return err
}

huangapple
  • 本文由 发表于 2022年8月13日 02:59:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/73338679.html
匿名

发表评论

匿名网友

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

确定