无法在C++中创建SQLite表(android)

Can't create SQLite table in C++ (android)

本文关键字:android SQLite 创建 C++      更新时间:2023-10-16

我正在制作一个Cocos2DX(C )Android游戏,我正在尝试实现SQLite,但我什至无法创建表!

这是我打开数据库并在内部创建表的功能:

void HelloWorld::initDB() {
    #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
    std::string wpath = FileUtils::getInstance()->getWritablePath() + "save.db";
    FILE *f = fopen(wpath.c_str(), "r");
    if (f == NULL) {
        firstLogin = true;
    } else {
        firstLogin = false;
    }
    fclose(f);
    #endif
    int result;
    result = sqlite3_open(wpath.c_str(), &db);
    if (result != SQLITE_OK) {
        CCLOG("open database failed, number %d", result);
    }
    if(firstLogin) {
        sql_query("CREATE TABLE IF NOT EXISTS data(variable, value)");
        insertVariableInt("coins", 0);
        insertVariableInt("timesPlayed", 0);
        insertVariableInt("highScore", 0);
    }
}

这是我的 sql_query()函数:

int HelloWorld::sql_query(const char * query,int (*callback)(void*,int,char**,char**), void* data)
    {
    char* errMsg = 0;
    int result = sqlite3_exec(db, query, callback, data, &errMsg);
    if (errMsg)  {
        CCLOG("SQLite3: %s", errMsg);
        sqlite3_free(errMsg);
    }
    return result;
}

当我运行游戏时, save.db 是创建文件,但里面没有表,它是空的!(0字节)。而且它没有给我任何错误,它给了我一个空的save.db文件。

我该如何解决这个问题?谢谢!

我测试了您的代码,我可以创建data表。

SQLite version 3.16.2 2017-01-06 16:32:41
Enter ".help" for usage hints.
sqlite> .tables
data

我看到您只使用一个参数调用sql_query。您是否超载该方法或定义了默认参数值?无论如何,这是我使用的代码。请注意,您可以致电isFileExist而不是fopen

MainMenu::MainMenu() {
  std::string wpath = FileUtils::getInstance()->getWritablePath() + "save.db";
    bool firstLogin = FileUtils::getInstance()->isFileExist(wpath);
    int result = sqlite3_open(wpath.c_str(), &db);
    if (result != SQLITE_OK) {
        CCLOG("open database failed, number %d", result);
    }
    if(firstLogin) {
        sql_query("CREATE TABLE IF NOT EXISTS data(variable, value)", nullptr, nullptr);
    }
}
int MainMenu::sql_query(const char * query,int (*callback)(void*,int,char**,char**), void* data)
{
    char* errMsg = 0;
    int result = sqlite3_exec(db, query, callback, data, &errMsg);
    if (errMsg)  {
        CCLOG("SQLite3: %s", errMsg);
        sqlite3_free(errMsg);
    }
    return result;
}