如何在不使用Next()的情况下获取sql.Rows的计数? [英] How to get count of sql.Rows without using Next()?

查看:86
本文介绍了如何在不使用Next()的情况下获取sql.Rows的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取 * sql.Rows 之前的长度,然后开始执行Next()循环以获取值。一种方法是通过两次遍历Next(),获取计数,然后遍历该新切片以拉出值来创建行的切片,但这似乎效率很低,所以我希望有一种更好的方法做这个。

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.

看文档,我看不到我可以使用的Count函数或Length函数: https://golang.org/pkg/database/sql/#Rows

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

在Go代码中,我看不到任何对我有帮助的结构(尽管我可能会遗漏某些东西,因此请再欣赏一下这里): https://github.com/golang/go/blob/master/src/database/sql/sql。 go#L1714

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

肯定有某种方法比只循环遍历Next()更好吗?

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

我意识到我也可以做一个单独的计数查询,甚至可以在另一个选择中包含一个count(*),但是我也想避免这种情况。这是一个Go ORM项目,我不想使select语句复杂化,我宁愿避免尽可能多地篡改其构建请求。

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.

谢谢。

推荐答案

您基本上列出了您的选择。没有隐藏的功能可以为您提供行数。

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.

还要注意,如果您打算遍历行并以任何方式读取它们,则意味着可以忽略的开销,您不必担心。如果行数确实很大,并且查询返回许多数据,并且您希望避免为所有内存分配内存,那么请预先执行 SELECT COUNT(*)查询,这样您就可以知道结果的数量(但知道如果同时插入或更新记录,下一次查询可能会改变)。

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).

这篇关于如何在不使用Next()的情况下获取sql.Rows的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆