繁体   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