How to get count of sql.Rows without using Next()?

这一生的挚爱 提交于 2020-02-29 17:48:25

问题


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:


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



来源:https://stackoverflow.com/questions/37629357/how-to-get-count-of-sql-rows-without-using-next

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!