使用数据库/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.