dongnai2804 2016-09-30 04:36
浏览 310
已采纳

如何查找从db.Query postgres返回的行数

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?

  • 写回答

2条回答 默认 最新

  • dongzhui4927 2016-09-30 08:02
    关注

    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")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大