cocos2dx中web+json+sqlite整合demo

这个demo是web+json+sprite的整合例子,还差一个多线程(以后补上)。


#ifndef zj1999_CCBMainPage_h
#define zj1999_CCBMainPage_h

#include "CcbBase.h"
#include "sqlite3.h"
#include "curl/curl.h"
#include "json/json.h"

#define DB_NAME "test.db"
class CCBMainPage: public CcbBase {
private:
    sqlite3 *pDB;
public:
    CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(CCBMainPage, create);
    
    CCBMainPage() { }
    
    virtual ~CCBMainPage() { }
    
    virtual cocos2d::SEL_MenuHandler onResolveCCBCCMenuItemSelector(cocos2d::CCObject * pTarget, const char * pSelectorName) ;
    
    void openDB(const char* dbname) {
        char * errMsg = NULL;//错误信息
        std::string filename = CCFileUtils::sharedFileUtils()->fullPathForFilename(dbname);
        int result = sqlite3_open(filename.c_str(), &pDB);
        if( result != SQLITE_OK )
            CCLog( "打开数据库失败,错误码:%d ,错误原因:%s\n" , result, errMsg );
        else
            CCLog("成功地打开了数据库");
    }
    void closeDB() {
        sqlite3_close(pDB);
    }
    void exec(const char* sql) {
        int result;
        char * errMsg = NULL;
        result=sqlite3_exec( pDB, sql , NULL, NULL, &errMsg );
        if( result != SQLITE_OK )
            CCLog( "错误码:%d ,错误原因:%s\n, sql: %s" , result, errMsg, sql );
        else
            CCLog("sql Ok!");
    }
    
    void insertSql(const char* sql) {
        openDB(DB_NAME);
        exec(sql);
        closeDB();
    }
    
    void onHeroPage(cocos2d::CCObject *pSender);
    void onShengjiPage(cocos2d::CCObject *pSender) {
        CCLog("begin to test the sqlite");
        
        openDB(DB_NAME);
        exec("create table role( ID integer primary key autoincrement, jobId integer, jobName text, jobIcon text, description text, createTime text ) ");
        closeDB();
    }
    
    static int callback(void *NotUsed, int argc, char **argv, char **azColName)
    {
        NotUsed = 0;
        int i;
        for (i = 0; i < argc; i++)
        {
            printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
        }
        printf("\n");
        return 0;
    }
    void onJinghuaPage(cocos2d::CCObject *pSender) {
        CCLog("network test!!");
        CURL* curl;
        CURLcode res;
        curl_global_init(CURL_GLOBAL_DEFAULT);
        curl = curl_easy_init();
        
        if(curl) {
            std::string jsonStr;
            curl_easy_setopt(curl, CURLOPT_URL, "http://172.16.9.71:11111/data/game/job.ashx?op=l");
            curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, &jsonStr);
            res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
            if(res!=CURLE_OK) {
                CCLog("curl_easy_setopt not return CURL_OK");
            } else {
                CCLog("curl_easy_setopt exec success");
            }
            res = curl_easy_perform(curl);
            if(res!=CURLE_OK) {
                CCLog("curl_easy_perform not return CURLE_OK");
            } else {
                CCLog("curl_easy_perform exec success");
            }
            curl_easy_cleanup(curl);
            
            parseJson(jsonStr);
        }
        
    }
    static size_t write_data(void* buffer, size_t size, size_t nmemb, void* userData) {
        CCLog("writeData!!!");
        std::string& str = *((std::string*)userData); //注意:这里要使用引用;
        str += (char*) buffer;
        return size*nmemb;
    }
    void parseJson(std::string jsonData) {
        Json::Reader reader;
        Json::Value root;
        if (reader.parse(jsonData.c_str(), root))
        {
            int size = root["rows"].size();
            for (int i=0; i<size; i++) {
                Json::Value row = root["rows"][i];
                char sql[1000];
                sprintf(sql, "insert into role values(NULL, %d, '%s', '%s', '%s', '%s')", 
                        row["JobId"].asInt(), row["JobName"].asString().c_str(), row["JobIcon"].asString().c_str(),
                        row["Description"].asString().c_str(), row["CreateTime"].asString().c_str());
                CCLog(sql);
                insertSql(sql);
            }
        }
       
    }
    void onJiangliPage(cocos2d::CCObject *pSender) {
        CCLog("jsonTest");
        openDB(DB_NAME);
        sqlite3_exec(pDB, "select * from role", callback, 0, NULL);
        closeDB();

    }
    void onSuipianPage(cocos2d::CCObject *pSender) {
        CCLog("onSuipianPage");
    }
    void onJinengxueyuanPage(cocos2d::CCObject *pSender) {
        CCLog("onJinengxueyuanPage");
    }
};

/* Forward declaration. */
class CCBReader;

class CCBMainPageLoader : public cocos2d::extension::CCLayerLoader {
public:
    static CCScene* loadCcbi() ;

public:
    CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCBMainPageLoader, loader);
    
protected:
    CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCBMainPage);
};


#endif


json参考文章

http://blog.csdn.net/yanghuiliu/article/details/8061888
http://blog.csdn.net/yanghuiliu/article/details/7765868
http://blog.csdn.net/ashqal/article/details/8573392

json的使用
http://www.cnblogs.com/lidabo/archive/2012/10/31/2748026.html


curl代码需要一个回调函数来进行数据的纪录。
参考例子:http://bbs.chinaunix.net/thread-3755115-1-1.html

        CURL* curl;
        CURLcode res;
       // char buf[2048];
        
        curl_global_init(CURL_GLOBAL_DEFAULT);
        curl = curl_easy_init();
        if(curl) {
            curl_easy_setopt(curl, CURLOPT_URL, "http://172.16.9.71:11111/data/game/job.ashx?op=l");
            curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
            res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
            if(res!=CURLE_OK) {
                CCLog("curl_easy_setopt not return CURL_OK");
            } else {
                CCLog("curl_easy_setopt exec success");
            }
//            curl_easy_setopt(curl, CURLOPT_WRITEDATA, buf);
            res = curl_easy_perform(curl);
            if(res!=CURLE_OK) {
                CCLog("curl_easy_perform not return CURLE_OK");
            } else {
                CCLog("curl_easy_perform exec success");
            }
            curl_easy_cleanup(curl);
        }


回调函数如下:

 static size_t write_data(void* buffer, size_t size, size_t nmemb, void* userp) {
        CCLog("%s", (char*)buffer);
        return size*nmemb;
    }




你可能感兴趣的:(cocos2dx)