C++ populate vector from sqlite3 callback function? -
i have sqlite3 table "addresses" this:
+----+------+--------+ | id | name | number | +----+------+--------+ | 1 | john | 413434 | +----+------+--------+
and want populate global vector, able use somewhere else , join other data. far, have this:
... #include <sqlite3.h> using namespace std; static int callbackdb(void *notused, int argc, char **argv, char **szcolname) { for(int = 0; < argc; i++) cout << szcolname[i] << " = " << argv[i] << endl; return 0; } int main(int argc, char* argv[]) { vector<vector<string> > table; for( int = 0; < 2; i++ ) table.push_back(std::vector< std::string >()); sqlite3 *db; char *szerrmsg = 0; // open database int rc = sqlite3_open("database.db", &db); const char *query; query = "select * addresses"; rc = sqlite3_exec(db, query, callbackdb, 0, &szerrmsg); return 0; }
how results in vector or in other way i'll able use easier?
the fourth parameter of sqlite3_exec
can used pass information callback. in case, pointer table
useful:
typedef vector<vector<string> > table_type; static int callbackdb(void *ptr, int argc, char* argv[], char* cols[]) { table_type* table = static_cast<table_type*>(ptr); vector<string> row; (int = 0; < argc; i++) row.push_back(argv[i] ? argv[i] : "(null)"); table->push_back(row); return 0; } ... rc = sqlite3_exec(db, query, callbackdb, &table, &errmsg);
however, using callbacks not useful because bunch of naked strings. should rather use prepare/step/finalize interface directly can use proper data types:
class address { public: address(int id, const string& name, const string& number); ... } ... vector<address> addresses; sqlite3_stmt *stmt; rc = sqlite3_prepare_v2(db, "select id, name, number addresses", -1, &stmt, null); if (rc != sqlite_ok) { cerr << "select failed: " << sqlite3_errmsg(db) << endl; return ...; // or throw } while ((rc = sqlite3_step(stmt)) == sqlite_row) { int id = sqlite3_column_int(stmt, 0); const char* name = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1)); const char* number = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2)); // let's assume number can null: addresses.push_back(address(id, name, number ? number : "")); } if (rc != sqlite_done) { cerr << "select failed: " << sqlite3_errmsg(db) << endl; // if return/throw here, don't forget finalize } sqlite3_finalize(stmt);
Comments
Post a Comment