Hi All,I am a php programmer before, the 2 dimensional array with key-value is pretty easy to read and write in PHP.
now,I am trying to write a normal app using cocos2dx, and need read a data set from sqlite db.
Is there a easy way to read/write a 2 dimensional array with key-value in c++ ?
DataSet like :
$user_table = array ( 0 => array ( "UserName" => "coco", "pw" => "abc","Adress" => "12,xxxxxx,China"),
1 => array ( "UserName" => "Bill Gate", "pw" => "edt","Adress" => "22,xxxxxx,USA"),
2 => array ( "UserName" => "Jonathan Ive", "pw" => "dcd","Adress" => "33,xxxxxx,USA"),
);
Found a solution :
Using CCArray~~>[ CCArray~~> CCDictionary ( key-value ) ]
// Get Record (Without callback)
CCArray* SqlUtil:: getDataSet(string sql){
// int count;
sqlite3_stmt * statement;
CCArray * dataSet = new CCArray;
sqlite3_prepare_v2(pDB, sql.c_str(),-1,&statement, NULL);
while(sqlite3_step(statement)==SQLITE_ROW){
CCDictionary * feild = CCDictionary::create();
CCArray * record = new CCArray;
int num_column = sqlite3_column_count(statement);
int i;
string textValue;
for(i = 0; i < num_column; ++i)
{
//CCLog("{ key1-name: %s }", sqlite3_column_name(statement,i));
switch(sqlite3_column_type(statement,i)) {
case SQLITE_TEXT:
textValue = string(reinterpret_cast(sqlite3_column_text(statement,i)));
break;
case SQLITE_INTEGER:
textValue = DataTypeConvert::i2s(sqlite3_column_int(statement,i));
break;
case SQLITE_NULL:
textValue="NULL";
break;
default:
break;
}
feild->setObject(CCString::create(textValue), sqlite3_column_name(statement,i));
CCString* pStr1 = (CCString*)feild->objectForKey(sqlite3_column_name(statement,i));
record->addObject(feild);
}
dataSet->addObject(record);
}
//-----------------Start : example for read Record set------------------
/*
CCObject * it = NULL;
CCARRAY_FOREACH(dataSet, it){
CCObject *it2=NULL;
CCArray* recordItem = static_cast(it);
CCARRAY_FOREACH(recordItem, it2){
CCDictionary* fields = static_cast(it2);
CCDictElement* pElement;
//----------Print recrod-----------------------------------------------------
//get field by key
CCString* pStr = (CCString*)fields->objectForKey("cardId");
CCLog("{ key1: %s }", pStr->getCString());
CCDICT_FOREACH(fields, pElement){
CCString* value = (CCString*)pElement->getObject();
CCLOG("%s : %s",pElement->getStrKey(),value->getCString());
}
//-------------------------------------------------------------
}
}
*/
//-----------------End : example for read Record set------------------
sqlite3_finalize(statement);
return dataSet;
}
Jgod
June 18, 2013, 9:55am
#3
You can also use std::map in c++, using anything as the key (probably a string) and anything as the value (a struct or object in your case)