How do I get the number of rows returned while using database/sql?

后端 未结 2 488
闹比i
闹比i 2021-01-28 01:41

Given the following function:

func (me *OrderService) GetOrders(orderTx *sql.Tx, orderId int) (orders *sql.Rows) {
    orders, err := ecommTx.Query(\"SELECT * FR         


        
2条回答
  •  孤独总比滥情好
    2021-01-28 02:35

    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)
    

    You are not adding any extra overhead by doing so. Other languages, such as C# or Delphi, 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.

提交回复
热议问题