使用数据库(如sqlite)与cocos2d-x配合使用。

5
我正在开始在iPhone上构建一款游戏应用。我使用cocos2d-x游戏引擎,因为从那里很容易移植到Android平台。此外,编码是用C++完成的,而我非常熟悉这门语言。我想知道是否有办法在cocos2d-x中使用任何数据库。虽然sqlite是首选但不是必须的。我的数据库中将有大约1/2 MB的数据。所以,是的,我考虑过使用内存数据库,但我希望我的读/写查询能够高效地运行。

我查阅了一些博客,其中建议我可能需要使用sqlite的C ++包装器。问题是,对于一个独立的C ++代码,我可以设置环境,但如何集成到xcode(在mac os中)中以使用sqlite与cocos2d-x呢?

3个回答

2

原始帖子位于http://www.cocos2d-x.org/boards/6/topics/7006

我发现了一个最简单的方法来将sqlite添加到cocos2dx游戏中。

那就是,从sqlite3 c++ api下载源代码,并将sqlite3.c添加到Android.mk中。

然后将这些代码编译为您的cocos2dx代码。

当您需要使用它时,在您的代码中包含sqlite.h。

以下是我的示例代码,用于对数据库进行操作:

sqlite3 *pDB = NULL;
char* errMsg = NULL;
string sqlstr;
int result;
string dbPath = CCFileUtils::getWriteablePath();
dbPath.append("Settings.db");
result = sqlite3_open(dbPath.c_str(),&pDB);
if (result != SQLITE_OK)
    CCLOG("OPENING WRONG, %d, MSG:%s",result,errMsg);

bool isExisted_;
sqlstr = "select count(type) from sqlite_master where type='table' and name='YourTableName'";
result = sqlite3_exec(pDB, sqlstr.c_str(), isExisted, &isExisted_, &errMsg);
if(result != SQLITE_OK)
    CCLOG("check exist fail %d Msg: %s", result, errMsg);
result = sqlite3_exec(pDB, "create table YourTableName(ID INTEGER primary key autoincrement, name varchar(32), type INT, posX INT, posY INT, isUnlock INT)",NULL,NULL,&errMsg);
if(result != SQLITE_OK)
    CCLOG("CREATE TABLE FAIL %d, Msg: %s",result,errMsg);
sqlite3_close(pDB);

你说“Sqlite c++ api”,但我在Sqlite网站上没有找到任何相关内容,而且我从他们那里得到的下载文件是C语言(因此是.c),而不是c ++。我是否遗漏了什么或它们是相同的? - owen gerig
1
@owengerig 这是我的问题。它实际上是C语言,你可以在C++代码中毫无问题地使用它。 - m.ding

1

我认为最好的方法是:

整个主题在这里:http://www.cocos2d-x.org/boards/6/topics/7006 示例代码 :)
CCFileUtils* fileUtils = CCFileUtils::sharedFileUtils();
unsigned long size = 5;

unsigned char* smth;
smth = fileUtils->getFileData("koalalocker","r",&size);

printf("Size: %lu\n\n",size);
fflush(stdout);

if(cos == NULL)
    {
    LOG("can't open");
            return;
    }
else
    LOG("I have something!");

string path = fileUtils->getWriteablePath();
path += "test_OUT";

char buffer[300];
sprintf(buffer,"PATH: %s\n",path.c_str());
LOG(buffer);
std::fstream outfile(path.c_str(),std::fstream::out);
outfile.write((const char*)smth,size-1);
outfile.close();

LOGN("Size:",size);
LOG((const char*)smth);

1

SQLite已经集成在Android和IOS中,您只需要将其引用到您的项目中即可。 - Chale CS
1
@ChaleCS 兄弟,cocos2d-x 的情况有些不同。如果你想仅使用 c++ 和 cocos2d-x 框架来实现 sqlite 集成,而不涉及原生的 iOS (obj c) 和 Android (java) 代码,那么这篇博客会对你有所帮助。 - Rajan Maheshwari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接