dsh7623 2016-06-04 10:56
浏览 119

如何在不使用Next()的情况下获取sql.Rows的计数?

I need to get the length of *sql.Rows before I begin my Next() loop to get the values out. One way is to create a slice of rows by looping over Next() twice, getting the count, and then looping over that new slice to pull the values out, but that seems really inefficient so I'm hoping there is a better way to do this.

Looking at the docs, I see no mention of a Count function or Length function that I can use: https://golang.org/pkg/database/sql/#Rows

Looking at the Go code, I can't see anything in the struct that would help me (although I could be missing something, so would appreciate a second pair of eyes here): https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1714

Surely there is some way to do this that is better than just looping over Next() twice?

I realize I could do a separate count query as well, or even include a count(*) in my other select, but I'd rather avoid this too. This is for a Go ORM project, and I don't want to overcomplicate the select statement, and I'd rather avoid tampering with their built-up request as much as possible.

Thanks.

  • 写回答

1条回答 默认 最新

  • dontoften8899 2016-06-04 11:06
    关注

    You basically listed your options. There is no hidden feature that would supply you the rows count.

    Note that some db-specific driver might support this, but the general interface does not.

    Also note that if you plan to iterate over the rows and read them anyway, this means negligible overhead which you should not be concerned about. If the rows count is really big and the query returns many data and you want to avoid allocating memory for all, then execute a SELECT COUNT(*) query beforehand so you'll know the number of results (but know that it might change for the next query if records are inserted or updated meanwhile).

    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记