使用数据库/sql时如何获取返回的行数? [英] How do I get the number of rows returned while using database/sql?

查看:234
本文介绍了使用数据库/sql时如何获取返回的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供以下功能:

func (me *OrderService) GetOrders(orderTx *sql.Tx, orderId int) (orders *sql.Rows) {
    orders, err := ecommTx.Query("SELECT * FROM orders WHERE id=?", orderId)
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Successfully queried and receive %d orders", orders.count)
    return orders
}

是否有任何简单的方法来计算结果?我想保持此数据库引擎的竞争力,但FWIW ....我正在使用 Matt N的sqlite3驱动程序用于集成测试,但计划在产品中使用其他数据库.

Are there any easy ways to .count the results? I'd like to keep this database engine agonistic, but FWIW.... I'm using Matt N's sqlite3 driver for my integration tests, but plan on having a different DB in prod.

推荐答案

sql.Query()返回 * Rows . Rows 是阅读器,而不是集合,因此诸如 count() len()等的调用无关.您必须通读 Rows 才能知道有多少条目:

sql.Query() returns *Rows. Rows is a reader, not a collection, so calls such as count() or len() etc. are not relevant. You have to read through Rows to know how many entries you've got:

count := 0
for orders.Next() {
    count++
}

log.Printf("Successfully queried and receive %d orders", count)

您这样做不会增加任何额外的开销.其他可能返回具有 count 属性的集合的语言(例如C#或Delphi)只是为您进行阅读并将结果打包到集合中,以方便您使用.

You are not adding any extra overhead by doing so. Other languages, such as C# or Delp that might return a collection with a count property are simply doing the reading for you and packaging the results into a collection for your convenience.

这篇关于使用数据库/sql时如何获取返回的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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