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

我开始在iPhone上构build一个游戏应用程序。 我使用的是cocos2d-x游戏引擎,因为它很容易从那里移植到android。 此外,编码是在C ++,我非常熟悉。 我想知道是否有办法使用任何数据库与cocos2d-x。 虽然sqlite是首选,但不是强制性的。 我将在数据库中有大约1/2 mb的数据。 所以,是的,我也想过保留/使用内存数据库,但我希望我的读/写查询是省时的。

我查了一些博客,这表明我可能需要使用C ++包装的SQLite。 问题是,对于一个独立的C ++代码,我可以设置环境,但是如何将它集成到xcode(在mac os中)以使用带有cocos2d-x的sqlite。

原帖在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); 

我认为最好的办法是:

  • 用CCFileUtils :: getFileData()打开文件,你会得到你的文件数据。 例如你的sqlite文件:)

  • 使用CCFileUtils :: getWriteablePath()来获取您可以编写的目录。

  • 例如使用fstream将数据写入到以前的目录

  • 现在,您可以使用源代码从sqlite3 c ++ api访问数据库。

整个topis在这里: 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); 

我已经写了一个关于在xcode中一步一步地在cocos2d-x游戏中整合sqlite的博客。 你可以看到这个http://sqlite-integration-in-cocos2d-x.blogspot.in/