从db.query读取数据时,除了扫描(scan)之外,还有其他的方法吗?

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

Is there any way other than scan when reading data from db.query?

问题

当我使用Scan函数时,我必须事先将所有变量写入Scan函数中。我需要一种解决方案,可以使用类似sprintf的方式来使用数据。

有没有一种方法可以在不定义变量的情况下访问数据?

例如:

  1. row["unit_name"]

或者

  1. unit_name, unit_position string
  2. val := fmt.Sprintf("%s, %s", unit_name, unit_position_name)
  3. row[val]
英文:

When I use scan I have to write all the variables into the scan beforehand. i need a solution where i can use data using things like sprintf

Is there a way I can access the data without defining a variable?

  1. func (dbs *item) ReadQuery() {
  2. var (
  3. unit_name, unit_position_name string
  4. )
  5. rows, err := db.Query(dbs.query)
  6. for rows.Next() {
  7. rows.Scan(&unit_name, &unit_position_name)
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. }
  12. }

for example;

  1. row["unit_name"]

or

  1. unit_name,unit_position string
  2. val:= fmt.Sprintf("%s , %s",unit_name,unit_position_name)
  3. row[val]

答案1

得分: 2

以下是翻译好的内容:

这是如何在不显式声明行值变量的情况下扫描一行的方法。

为值创建一个切片。使用这些值的地址创建一个切片。扫描到这些地址。

  1. func example(db *sql.DB, query string) {
  2. rows, err := db.Query(query)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. cols, err := rows.Columns()
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. addrs := make([]interface{}, len(cols))
  11. for rows.Next() {
  12. values := make([]interface{}, len(cols))
  13. for i := range addrs {
  14. addrs[i] = &values[i]
  15. }
  16. err := rows.Scan(addrs...)
  17. if err != nil {
  18. log.Fatal(err)
  19. }
  20. // 变量 values 包含了行的值。
  21. // 这是一个使用 values 的示例。
  22. // 用你自己的代码替换 for 循环来处理行。
  23. for i := range cols {
  24. fmt.Printf("%s: %v\n", cols[i], values[i])
  25. }
  26. }
  27. }

希望对你有帮助!

英文:

Here's how to scan a row without explicitly declaring a variable for value in the row.

Make a slice for the values. Make a slice with the address of those values. Scan to the addresses.

  1. func example(db *sql.DB, query string) {
  2. rows, err := db.Query(query)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. cols, err := rows.Columns()
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. addrs := make([]any, len(cols))
  11. for rows.Next() {
  12. values := make([]any, len(cols))
  13. for i := range addrs {
  14. addrs[i] = &values[i]
  15. }
  16. rows.Scan(addrs...)
  17. if err != nil {
  18. log.Fatal(err)
  19. }
  20. // The variable values contains the row values.
  21. // Here's an example of how to use the values.
  22. // Replace the for loop with your code to
  23. // process the row.
  24. for i := range cols {
  25. fmt.Printf("%s: %v\n", cols[i], values[i])
  26. }
  27. }
  28. }

huangapple
  • 本文由 发表于 2022年10月6日 23:50:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/73976729.html
匿名

发表评论

匿名网友

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

确定