2013-04-05 51 views
2

我有一個sqlite3的表「地址」是這樣的:從sqlite3回調函數C++填充矢量?

+----+------+--------+ 
| ID | name | number | 
+----+------+--------+ 
| 1 | John | 413434 | 
+----+------+--------+ 

,我想填充全局向量,這也是我能夠在其他地方使用,並與其他一些數據加入。 到目前爲止,我有這個:

... 
#include <sqlite3.h> 

using namespace std; 

static int callbackDB(void *NotUsed, int argc, char **argv, char **szColName) 
{ 
    for(int i = 0; i < argc; i++) 
     cout << szColName[i] << " = " << argv[i] << endl; 

    return 0; 
} 

int main(int argc, char* argv[]) { 
    vector<vector<string> > table; 
    for(int i = 0; i < 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 * FROM addresses"; 

    rc = sqlite3_exec(db, query, callbackDB, 0, &szErrMsg); 

    return 0; 
} 

我怎麼能得到載體或以其他方式,這樣我就可以使用它更容易的結果嗎?

+0

你爲什麼不就中SQL加入? – 2013-04-05 14:26:10

+0

我其實不瞭解你? – booka 2013-04-05 14:27:26

+0

您想要加入地址數據還有哪些其他數據? – 2013-04-05 14:30:20

回答

5

sqlite3_exec的第四個參數可用於將信息傳遞給回調。 在你的情況,一個指向table將是有益的:

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; 
    for (int i = 0; i < argc; i++) 
     row.push_back(argv[i] ? argv[i] : "(NULL)"); 
    table->push_back(row); 
    return 0; 
} 
... 
    rc = sqlite3_exec(db, query, callbackDB, &table, &errmsg); 

但是,在使用回調喜歡這樣,因爲你得到的只是一堆裸體的字符串是不是非常有用。 你還是使用準備/步/直接完成界面,使您可以使用適當的數據類型:

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 FROM 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 be NULL: 
     addresses.push_back(Address(id, name, number ? number : "")); 
    } 
    if (rc != SQLITE_DONE) { 
     cerr << "SELECT failed: " << sqlite3_errmsg(db) << endl; 
     // if you return/throw here, don't forget the finalize 
    } 
    sqlite3_finalize(stmt); 
+0

太好了,謝謝。我做到了:「vector >&ptr = *(vector > *)table;」 – booka 2013-04-08 02:27:52