如何查找从db.Query postgres返回的行数 [英] How to find the rows count returned from db.Query postgres

查看:132
本文介绍了如何查找从db.Query postgres返回的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  rows,err:= db。

我使用goLang lib / pq驱动程序并尝试从数据库提取行。 Query(select id,name from mytable limit 5)

我想要一个if else子句它检查结果集中是否有行,并且我这样做:

  if(!rows.Next()){
log.Printf(no rows returned)
} else {
log.Printf(rows returned)
}

但是总是会返回1个记录,我假设它是因为如果子句跳过一条记录因为只要我删除 if 子句,我就可以正确地获取所有记录。我怎样才能知道从select查询返回的行数而不执行其他查询? 当您使用对象,没有任何助手方法可以在一步中为您提供总行数。



一个简单但速度较慢的解决方案是使用增量变量遍历所有结果以存储行数:

  //错误处理省略
rows,_:= db.Query(SELECT * FROM table)
推迟rows.Close()

counter:= 0
for rows.Next(){
//如果您以后需要它们,您甚至可以扫描并存储结果
counter ++
}

fmt.Println(我们有,计数器,行)

否则,如果您的目标只是计数行数,请使用更专用的查询并使用 QueryRow

  //错误处理省略
var counter int

db.QueryRow(SELECT count(*)FROM table)。扫描(&计数器)

fmt.Println(我们有,计数器,行)


I am using goLang lib/pq driver and trying to fetch rows from database.

rows, err := db.Query("select id, name from mytable limit 5")

I want to have a if else clause which checks if there are rows in result set and I did this:

if(!rows.Next()){
   log.Printf("no rows returned")
} else {
   log.Printf("rows returned")
}

but this always return me 1 record less and I assume its because of the if clause it skips one record because as soon as I remove if clause I get all records correctly. How can I know the count of rows returned from the select query without executing another query?

解决方案

When you work with the Rows object, there isn't any helper method that give you the total rows count in one step.

A simple but slower solution is to iterate through all the results using an incremental variable to store the amount of rows:

// error handling omitted
rows, _ := db.Query("SELECT * FROM table")
defer rows.Close()

counter := 0
for rows.Next() {
 // you can even scan+store the result if you need them later
 counter++
}

fmt.Println("we have", counter, "rows")

Otherwise, if your goal is only to "count" the amount of rows, use a more dedicated query with QueryRow

// error handling omitted
var counter int

db.QueryRow("SELECT count(*) FROM table").Scan(&counter)

fmt.Println("we have", counter, "rows")

这篇关于如何查找从db.Query postgres返回的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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