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

后端 未结 2 534
闹比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:31

    There is no portable way to know the number of rows returned by a statement in advance, meaning without iterating through the returned cursor and counting.

    There are two typical solutions to this:

    • Run a separate COUNT(*) query. The problem with this approach is that it's very racy (the result set can be modified between the two queries, at least in some transaction isolation modes), so it is really only useful for things like pagers where you do a query that returns only part of the result set, and want to know how many other rows there are.

    • Iterate through the cursor and count. In Go, that means calling .Next() and then .Scan the result into your Order struct.

提交回复
热议问题