如何使用C ++从sqlite3数据库中获取数据?

时间:2015-09-29 20:50:38

标签: c++ sqlite

我是c ++的新手,如何在我的SqliteUtil类中使用SELECT查询和回调方法从sqlite3 db中检索数据?

我知道可以使用回调方法

收集数据

方法方案readRecords() - > executeQuery() - > sqlite3_exec(回调)

SqliteUtil.cpp

istream& operator>>(istream& is, Book& rhs){
    // just a suggestion: it is better if there is no input to do nothing
    if(!is) return is;
    string title, author;
    int number;
    char par1, comma, par2;
    cin >> skipws >> par1 >> title >> comma >> author>> comma >> number >> par2;
    if (par1 != '(' || comma != ',' || par1 != ')'){
        // set failbit to indicate invalid input format
        is.clear(ios_base::failbit);
    }
    rhs(title, author, number); 
    return is;
}

SqliteUtil.hpp

#include "SqliteUtil.hpp"

// for readRecords method
**static int SqliteUtil::callback(?char *record?, int argc, char **argv, char **azColName) {
    for(int i=0; i < argc; i++){
        cout <<     azColName[i];
        cout << "\t";
        cout << argv[i] ? argv[i] : "NULL";
        cout << "\n";
    }
    cout << "\n";**
    return 0;
}

// Thats execute query, just for DRY.
void SqliteUtil::executeQuery(string sql) {
    sql += ";";
    int result = sqlite3_exec(db, sql.c_str(), callback, ?records_s?, &zErrMsg);
    printError(result);
}


void SqliteUtil::readRecords(vector<string> columns = {}, vector<string> order = {}) {
    string sql = "SELECT";
    if (columns.size() == 0 ) {
        sql += " * ";
    } else {
        sql += " " + joinStrArray(columns) + " ";
    }
    sql += "from " + table;

    if (order.size() != 0) {
        sql += " ORDER BY " + joinStrArray(order) + " ASC";
    }

    executeQuery(sql);
}

0 个答案:

没有答案