How To Get SQLite Records in Single Class Method i

2019-06-26 17:56发布

问题:

In this example...

http://www.sqlite.org/quickstart.html

...I see how to use sqlite3_exec() with a callback class method or function in order to get a recordset and iterate through it.

Well, what if I want to create a class DB and have a static class method

static void * getRS(void *hDB,std::string sSQL) ?

I'm kind of new with C++ but getting the hang of it extremely rapidly. Is there a way in C++ to create like a Lambda function, get the results from that, and pass them back? Or, is there another technique to return a std::map, std::multimap, etc. that I can iterate through each row?

(Note, I'm using XCode and calling C++ from a db.static.mm file in my Objective C project, if that matters.)

This question is not a duplicate of sqlite3_exec() Callback function Clarification. In that question, the author asks essentially how the callback is used in sqlite3_exec(). In my question, I'm asking how to do a top-down approach of SQLite3 code instead of using a callback. It just so happens that someone left an answer (not the approved answer, mind you) that solves my problem, not that author's problem.

回答1:

The best solution to do this in a top-down (rather than callback) manner is to not use sqlite3_exec(). Instead, do it with sqlite3_prepare_v2(), sqlite3_step(), and then sqlite3_finalize(). Optionally, one can inject/bind query parameters with various sqlite3_bind_*() calls.

Here's an example of the proper code for that.