簡體   English   中英

在 Visual C++ 中使用 sqlite3

[英]Using sqlite3 in visual c++

我正在使用 Visual Studio 2015 並且我想將 sqlite3 與它一起使用,我已經設法將 sqlite3 集成到其中,但我只能通過本機 c 樣式使用它,我不能像在 c++ 中那樣使用類使用 sqlite。 我的數據庫中有一個表測試,其中包含值 (id int , id1 int , name string) 例如這個程序運行良好

void forprinting(string a)
{
    cout  << a<<"\n";
}
 int callback(void *NotUsed, int argc, char **argv, char **azColName) {
    int i;
    string testing;
    string test2;
       for (i = 0; i<argc; i++) 
       {
          testing = testing + azColName[i];//irrelevant
          test2 += argv[i];
       }
    forprinting(test2);
    printf("\n");
    return 0;
}



int main()
{
    char *zErrMsg = 0;
    sqlite3 *db;
    int rc;
    rc = sqlite3_open("DATA.db", &db);
    char *data;
    const char *sql;
    sql = "SELECT * FROM test;";
    sqlite3_exec(db, sql, callback, 0, &zErrMsg);
     sqlite3_close(db);
    system("pause");
    return 0;
}

這個程序的輸出是 0 0 測試,這很好,但是當我嘗試使用類實現相同的邏輯時,我在這里收到錯誤

#include <iostream>
#include <stdio.h>
using namespace std;
void forprinting(string a) {
    cout << a << "\n";
} 
class testingSqlite {
    public :
    int callback(void *NotUsed, int argc, char **argv, char **azColName) {
        int i;
        string testing;
        string test2;
        for (i = 0; i<argc; i++) {

            testing = testing + azColName[i];
            test2 += argv[i];
        }
        forprinting(test2);
        printf("\n");
        return 0;
    }
    void initiate() {
        char *zErrMsg = 0;
        sqlite3 *db;
        int rc;
        rc = sqlite3_open("DATA.db", &db);
        char *data;
        const char *sql;
        sql = "SELECT * FROM test;";
        sqlite3_exec(db, sql, callback, 0, &zErrMsg);
        sqlite3_close(db);

    }
};
int main()
{
    testingSqlite test1;
    test1.initiate();
    system("pause");
    return 0;
}

我知道在課堂上定義函數是一種不好的做法,但我很着急。 它正在給予

Error C3867 'testingSqlite::callback': non-standard syntax; use '&' to create a pointer to member



Error (active)      argument of type "int (testingSqlite::*)(void *NotUsed, int argc, char **argv, char **azColName)" is incompatible with parameter of type "int (*)(void *, int, char **, char **)"

我試圖更改函數參數來修復它,但沒有任何效果。

這個:

sqlite3_exec(db, sql, callback, 0, &zErrMsg);

應該:

sqlite3_exec(db, sql, &testingSqlite::callback, 0, &zErrMsg);

后者是正確的“成員”語法。 如果你曾經可以使用前者,它是非標准的(一些編譯器確實允許它)。 也就是說,它也不會工作,因為函數簽名並不表明它可以是成員函數。

相反,您可以使用參數列表的“void *”。

也就是說,您必須創建類似

int callback(void *o, int argc, char **argv, char **cname)
{
 testingSqlite op* = reinterpret_cast<testingSqlite *>(o);


 return op->callback( argc, argv, cname );
}

這意味着您在 tesingSqlite 中的回調不采用 void *

您還提供 c 樣式回調作為函數指針,而不是您的成員函數。 您還必須提供“this”指針作為第 4 個參數(當它給您回電時它變成 void *),例如:

sqlite3_exec( db, sql, callback, this, &zErrMsg );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM