登录
首页 >  Golang >  Go问答

使用 GORM 处理 GO lang 中 sql 的多个结果集

来源:stackoverflow

时间:2024-04-23 17:09:33 407浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《使用 GORM 处理 GO lang 中 sql 的多个结果集》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

之前的类似问题可以追溯到2012年,当时没有解决方案,所以我不得不重新提问。

struct type DualTable{
  table1 []Table1
  table2 []Table2
  }

  struct type Table1{
  A string
  B string
  }

  struct type Table2{
  P string
  Q string
  }

  var dualtable []DualTable
  var table1 []Table1
  var table2 []Table2

  func main(){
  //trial 1 :failed as i get only table1 result
  db.Raw("select * from table1 select * from table2").Scan(&table1).Scan(&table2)

    //trial 2 :failed as i get only table2 result
  db.Raw("select * from table2 select * from table1").Scan(&table1).Scan(&table2)

  //trial 3 : failed as got nothing
  db.Raw("select * from table1 select * from table2").Scan(&dualtable)
}

正如你所看到的,我正在尝试做什么。

我正在尝试在 dualtable 结构中获取两个表结果

但似乎只有第一个查询运行。

实际代码由非常长的结构组成,并且是机密的,因此我无法将其发布在这里。


解决方案


我想回答我自己的问题,因为我在这里没有找到解决方案,但不知何故找到了这个问题的解决方案,

2016 年之前你都做不到。

但是这种情况已经向 go 开发人员强调,因为这可能主要发生在执行发出多个结果集的存储过程时。

所有详细信息请参见此处: https://go-review.googlesource.com/c/go/+/30592/

简短摘要:查询首先为您提供第一个结果集,您可以从中获取结果。一旦你完成了它。使用

result.nextresultset()

gorm v1 本身不处理此问题,但您可以获取底层 *sql.rows 的查询结果,对表 1 调用 db.scanrows,对表 2 调用 rows.nextresultset 和 db.scanrows

var table1 []Table1
var table2 []Table2

func main()

    rows, err := db.Raw("select * from table1; select * from table2").Rows()

    err = db.ScanRows(rows, &table1)

    if rows.NextResultSet() {
        err = db.ScanRows(rows, &table2)
    } else {
        //only one result set was returned, handle this case
    }

}

终于介绍完啦!小伙伴们,这篇关于《使用 GORM 处理 GO lang 中 sql 的多个结果集》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>