ruben2020
ruben2020

Reputation: 1549

sqlite3_step and number of results

After I do a sqlite3_prepare_v2() of a statement, then I need to sqlite3_step() it.

For the moment, let's ignore all return values except SQLITE3_ROW and SQLITE3_DONE.

As long as the return value of sqlite3_step() is SQLITE3_ROW, I need to keep calling it, till I get all the results. Then the last return value would be SQLITE3_DONE.

I'm entering my results into a std::vector using push_back().

From what I've read, this should have an average complexity of O(log(n)) due to the resizing of the internal array of the vector. In order to reduce this complexity to O(1), I need to use reserve() of vector, before doing push_back().

But then from the sqlite3 API, I can't see a function that returns the total number of results that I would get, before I sqlite3_step() it.

How can I do this with sqlite3?

Upvotes: 2

Views: 2253

Answers (1)

user529758
user529758

Reputation:

First of all: did you benchmark it? Is this the bottleneck? If no, then just stop worrying about efficiency and complexity now, and goto end of answer.

Still here? OK, so let me tell you one more thing: resizing the vector may be of any complexity, it's up to the implementor of the C++ standard library. It may be O(1), O(n), O(log n), etc. But one thing is sure: if you have got N results from the database, you ain't no going to retrieve the data in O(n). Simply because you have... N results.

So I think that you should still not worry about this - vector is fast (assuming a reasonably high-quality standard library implementation). So go ahead and write that while loop and push_back() the elements one after another and that's it.

But, if you are still being scared by the slowness of poor old vector, then here's how you find the number of rows returned from a query - this is specific to SQLite:

SELECT COUNT(*) FROM the_table WHERE some_condition;

Also, there are a few more possibilities, as described in answers to this question.

Upvotes: 2

Related Questions