Use database (such as sqlite) with cocos2d-x

こ雲淡風輕ζ 提交于 2019-12-03 16:06:43

original post is at http://www.cocos2d-x.org/boards/6/topics/7006

I found that a easiest way to include sqlite to cocos2dx game.

That is, download the source code from sqlite3 c++ api, and add sqlite3.c to Android.mk.

Then compile these code as your cocos2dx code.

and include the sqlite.h in yourcode when you need to use it.

For operation on database following is my sample code:

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);

I think the best way is:

The whole topis is here: http://www.cocos2d-x.org/boards/6/topics/7006

Example code :)

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);

I have written a blog regarding integration of sqlite in a cocos2d-x game in xcode step by step. You can see this http://sqlite-integration-in-cocos2d-x.blogspot.in/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!