Use a database (e.g. sqlite) with cocos2d-x

I am starting to create a game application on iphone. I use the cocos2d-x game engine, as it is easy to port to Android. Also, coding takes place in C ++, which I am very familiar with. I want to know if there is a way to use any database with cocos2d-x. Although sqlite is preferred, but not required. I will have about 1/2 mb of data in the database. So yes, I was thinking about storing / using the database in memory, but I want my read / write requests to be time efficient.

I looked through some blogs that suggest that I might need to use the C ++ shell for sqlite. The problem is that for independent C ++ code I can configure the environment, but how to integrate it into xcode (on mac os) to use sqlite with cocos2d-x.

+5
source share
3 answers

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

I found that the easiest way to include sqlite in cocos2dx game.

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

Then compile this code as your cocos2dx code.

and include sqlite.h in your code when you need to use it.

To work with the database, the following example:

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);
+2
source

I think the best way:

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

All Articles