mysql++ (mysqlpp): how to get number of rows in result prior to iteration using fetch_row through UseQueryResult

StackOverflow https://stackoverflow.com/questions/22087618

  •  18-10-2022
  •  | 
  •  

Is there an API call provided by mysql++ to get the number of rows returned by the result?

I have code structured as follows:

// ...
Query q = conn.query(queryString);
if(mysqlpp::UseQueryResult res = query.use()){
    // some code

   while(mysqlpp::Row row = res.fetch_row()){


   }
}

My previous question here will be solved easily if a function that returns the number of rows of the result. I can use it to allocate memory of that size and fill in as I iterate row by row.

有帮助吗?

解决方案

In case anyone runs into this: I quote the user manual:

The most direct way to retrieve a result set is to use Query::store(). This returns a StoreQueryResult object, which derives from std::vector, making it a random-access container of Rows. In turn, each Row object is like a std::vector of String objects, one for each field in the result set. Therefore, you can treat StoreQueryResult as a two-dimensional array: you can get the 5th field on the 2nd row by simply saying result[1][4]. You can also access row elements by field name, like this: result[2]["price"].

AND

A less direct way of working with query results is to use Query::use(), which returns a UseQueryResult object. This class acts like an STL input iterator rather than a std::vector: you walk through your result set processing one row at a time, always going forward. You can’t seek around in the result set, and you can’t know how many results are in the set until you find the end. In payment for that inconvenience, you get better memory efficiency, because the entire result set doesn’t need to be stored in RAM. This is very useful when you need large result sets.

A suggestion found here: http://lists.mysql.com/plusplus/9047

is to use the COUNT(*) query and fetch that result and then use Query.use again. To avoid inconsistent count, one can wrap the two queries in one transaction as follows:

START TRANSACTION;
BEGIN;

SELECT COUNT(*) FROM myTable;

SELECT * FROM myTable;

COMMIT;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top