Cocos2d-x 分享一个封装的Sqlite3的DBUtil类

Cocos2d-x 分享一个封装的Sqlite3的DBUtil类,第1张

概述转载自:Cocos2d-x分享一个封装的Sqlite3的DBUtil类  在Cocos2d-x中使用Sqlite作为游戏持久化的解决方案是个不错的选择,使用json或者xml等文件存储的IO读写性能在手机设备上比较差,通常使用Xml和Json等文件存储数据时,因为实时的通过IO读取文件 *** 作非常耗时,往往在游戏启动的时候把数据读取出来放到游戏的缓存中,使用时去缓存中查询,这样会占用大量的内存,如果不

转载自:Cocos2d-x分享一个封装的Sqlite3的DBUtil类

在Cocos2d-x中使用sqlite作为游戏持久化的解决方案是个不错的选择,使用Json或者xml等文件存储的IO读写性能在手机设备上比较差,通常使用Xml和Json等文件存储数据时,因为实时的通过IO读取文件 *** 作非常耗时,往往在游戏启动的时候把数据读取出来放到游戏的缓存中,使用时去缓存中查询,这样会占用大量的内存,如果不想使用缓存的机制来查询,使用sqlite3数据库是个不错的解决方案,我做过测试,在拥有100条记录的表中查询出一条数据,只需要1ms,通常游戏的帧率设置为60,每一帧的时间为1/60秒=16ms,1ms的查询时间是可以接受的,在游戏中每一帧要做大量的 *** 作,cpu的逻辑运算,GPU的运算以及图形的渲染,如果1帧消耗的总时间>16ms,也就是线程Thread的sleep()的时间超过了16ms,则可能造成降帧,或者卡帧。所以数据读取对于游戏的性能影响还是很大的,一定要避免在游戏循环中进行文件的IO的 *** 作,数据库的IO *** 作也不行。

分享一个Cocos2d-x访问sqlite3数据库的单例的DBUitl类,对增删改查以及事务 *** 作等常用的API进行了一下简单的封装,还有很多不太完善的地方,希望大家帮我改进。

对Cocos3.x版本进行了封装。

使用方法很简单,直接在项目的dao层调用DBUtil::getInstance()->xxxMethod(params..)即可,这里就不列举使用的demo了,把DBUtil的实现源码贴一下。


3.x版


//  DBUtil.h  //  GuessMovIE  //  //  Created by apple on 14/11/24.  //  //    #ifndef __GuessMovIE__DBUtil__  #define __GuessMovIE__DBUtil__    #include "sqlite3.h"  #include "main.h"    USING_NS_CC;    class DBUtil {        private:            //数据库      sqlite3* m_pDataBase;        private:        #pragma mark <构造 && 析构>            DBUtil();            virtual ~DBUtil();            public :        #pragma mark <创建 && 销毁单例>            static DBUtil* getInstance();            static voID destoryInstance();        #pragma mark <数据库 *** 作>            /**      *  打开数据库(创建)      *      *  @param aDataBasename 数据库名      */      voID openDBWithname(std::string aDataBasename);            /**      *  关闭数据库      */      voID closeDB();            /**      *  创建数据表      *      *  @param asql       建表SQL语句      *  @param a@R_502_5991@name 表名      */      voID create@R_502_5991@(std::string asql,std::string a@R_502_5991@name);            /**      *  通过表名查询该表是否存在      *      *  @param aTabelname 表秒      *      *  @return true: 存在 false: 不存在      */      bool isExist@R_502_5991@Byname(std::string aTabelname);            /**      *  删除数据表      *      *  @param asql       删表SQL语句      *  @param a@R_502_5991@name 表名      */      voID delete@R_502_5991@(std::string asql,std::string a@R_502_5991@name);            /**      *  插入记录      *      *  @param asql 插入数据SQL语句      */      voID insertData(std::string asql);            /**      *  删除记录      *      *  @param asql 删除数据SQL语句      */      voID deleteData(std::string asql);            /**      *  修改记录      *      *  @param asql 修改数据SQL语句      */      voID updateData(std::string asql);            /**      *  查询记录      *      *  @param asql     修改数据SQL语句      */      std::vector<std::map<std::string,std::string> >searchData(std::string asql);            /**      *  查询记录的条数      *      *  @param sql 查询记录SQL语句      *      *  @return 记录条数      */      int searchDataCount(std::string asql);            /**      *  开始事务      *      *  @return  *** 作结果(sqlite3提供的宏)      */      int beginTransaction();            /**      *  提交事务(失败回滚)      *      *  @param aResult        *** 作结果      *      *  @return  *** 作结果(sqlite3提供的宏)      */      int comitTransaction(int aResult);        };    #endif /* defined(__GuessMovIE__DBUtil__) */



//  DBUtil.cpp  //  GuessMovIE  //  //  Created by apple on 14/11/24.  //  //    #include "DBUtil.h"    static DBUtil* s_pInstance = NulL;    const std::string cDBname = "gamedb";    #pragma mark <构造 && 析构>    DBUtil::DBUtil():m_pDataBase(NulL) {        }    DBUtil::~DBUtil() {        }    #pragma mark <创建 && 销毁单例>    DBUtil* DBUtil::getInstance() {      if (!s_pInstance) {          s_pInstance = new DBUtil();      }      return s_pInstance;  }    voID DBUtil::destoryInstance() {      delete s_pInstance;      s_pInstance = NulL;  }    #pragma mark <数据库 *** 作>    /**  *  打开数据库(创建)  *  *  @param aDataBasename 数据库名  */  voID DBUtil::openDBWithname(std::string aDataBasename) {      std::string writeablePath = fileUtils::getInstance()->getWri@R_502_5991@Path();      cclOG("path=%s",writeablePath.c_str());      std::string dbPath = writeablePath + aDataBasename;            int result = sqlite3_open(dbPath.c_str(),&m_pDataBase);      char* errMsg = NulL;      if (result != sqlITE_OK) {          log("打开数据库失败,错误码:%d,错误原因:%s\n",result,errMsg);      }            if (errMsg) {          sqlite3_free(errMsg);          errMsg = NulL;      }  }    /**  *  关闭数据库  */  voID DBUtil::closeDB() {      if (m_pDataBase) {          sqlite3_close(m_pDataBase);          m_pDataBase = NulL;      }  }    /**  *  创建数据表  *  *  @param asql       建表SQL语句  *  @param a@R_502_5991@name 表名  *  *  @usage string sql = "create @R_502_5991@ user(ID integer,username text,password text)";  */  voID DBUtil::create@R_502_5991@(std::string asql,std::string a@R_502_5991@name) {            openDBWithname(cDBname);            if (!isExist@R_502_5991@Byname(a@R_502_5991@name)) {          char* errMsg = NulL;          int result = sqlite3_exec(m_pDataBase,asql.c_str(),NulL,&errMsg);          if (result != sqlITE_OK) {              log("创建表失败,错误码:%d,错误原因:%s\n",errMsg);          }                    if (errMsg) {              sqlite3_free(errMsg);              errMsg = NulL;          }      }            closeDB();  }    /**  *  是否存在某张数据表的查询回调  *  *  @return 0  */  int isExist@R_502_5991@Callback(voID* para,int n_column,char ** column_value,char ** column_name) {      bool *isExisted_= (bool*)para;      *isExisted_= (**column_value) != '0';      return 0;  }    /**  *  通过表名查询该表是否存在  *  *  @param aTabelname 表秒  *  *  @return true: 存在 false: 不存在  */  bool DBUtil::isExist@R_502_5991@Byname(std::string aTabelname) {            if (m_pDataBase) {          //判断表是否存在          bool isExist;          char* errMsg = NulL;          std::string sql = "select count(type) from sqlite_master where type = '@R_502_5991@' and name = '" + aTabelname + "'";          int result = sqlite3_exec(m_pDataBase,sql.c_str(),isExist@R_502_5991@Callback,&isExist,&errMsg);                    if (result != sqlITE_OK) {              log("查询表是否存在失败,错误码:%d,错误原因:%s\n",errMsg);          }                    if (errMsg) {              sqlite3_free(errMsg);              errMsg = NulL;          }                    return isExist;      }            return false;  }    /**  *  删除数据表  *  *  @param asql       删表SQL语句  *  @param a@R_502_5991@name 表名  *  *  @usage string sql = "drop @R_502_5991@ name";  */  voID DBUtil::delete@R_502_5991@(std::string asql,std::string a@R_502_5991@name) {            openDBWithname(cDBname);            beginTransaction();            int result = 0;      if (isExist@R_502_5991@Byname(a@R_502_5991@name)) {          char* errMsg = NulL;          result = sqlite3_exec(m_pDataBase,errMsg);          }                    if (errMsg) {              sqlite3_free(errMsg);              errMsg = NulL;          }      }            comitTransaction(result);            closeDB();        }    /**  *  插入记录  *  *  @param asql 插入数据SQL语句  *  *  @usage string sql = "insert into User(name) values ('cc') ";  */  voID DBUtil::insertData(std::string asql) {            openDBWithname(cDBname);            beginTransaction();            char* errMsg = NulL;      int result = sqlite3_exec(m_pDataBase,&errMsg);      if (result != sqlITE_OK) {          log("插入记录失败,错误码:%d,错误原因:%s\n",errMsg );      }            if (errMsg) {          sqlite3_free(errMsg);          errMsg = NulL;      }            comitTransaction(result);            closeDB();  }    /**  *  删除记录  *  *  @param asql 插入数据SQL语句  *  *  @usage string sql = "delete from User where name = 'cc'";  */  voID DBUtil::deleteData(std::string asql) {            openDBWithname(cDBname);            beginTransaction();            char* errMsg = NulL;      int result = sqlite3_exec(m_pDataBase,&errMsg);      if (result != sqlITE_OK ) {          log("删除记录失败,错误码:%d,错误原因:%s\n",errMsg);      }            if (errMsg) {          sqlite3_free(errMsg);          errMsg = NulL;      }            comitTransaction(result);            closeDB();        }    /**  *  修改记录  *  *  @param asql 修改数据SQL语句  */  voID DBUtil::updateData(std::string asql) {            openDBWithname(cDBname);            beginTransaction();            char* errMsg = NulL;      int result = sqlite3_exec(m_pDataBase,&errMsg );      if (result != sqlITE_OK) {          log( "修改记录失败,错误码:%d,错误原因:%s\n",errMsg );      }            if (errMsg) {          sqlite3_free(errMsg);          errMsg = NulL;      }            comitTransaction(result);            closeDB();  }    /**  *  查询回调  *  *  @return 0  */  int searchDataCallback(voID* para,char** column_value,char** column_name ) {      std::map<std::string,std::string> mapResults ;      for (int i = 0; i < n_column; i++) {          mapResults.insert(std::make_pair<std::string,std::string>((std::string)column_name[i],(std::string)column_value[i]));      }      std::vector<std::map<std::string,std::string> >* vect = (std::vector<std::map<std::string,std::string> >*)para;      vect->push_back(mapResults);      return 0;  }      /**  *  查询记录  *  *  @param asql     查询数据SQL语句  */  std::vector<std::map<std::string,std::string> > DBUtil::searchData(std::string asql) {        //    long long int startTime = getNowTime();  //    cclOG("startTime=%lld",getNowTime());            openDBWithname(cDBname);            //vector是查询的结果集,每一个结果都存在map中      //map的第一string是key(字段名),第二个string是value(查询出的对应数据)      std::vector<std::map<std::string,std::string> > vec;            char* errMsg = NulL;      int result = sqlite3_exec(m_pDataBase,searchDataCallback,&vec,&errMsg);      if (result != sqlITE_OK) {          log("查询失败,错误码:%d,错误原因:%s\n",errMsg);      }            if (errMsg) {          sqlite3_free(errMsg);          errMsg = NulL;      }            closeDB();        //    long long int endTime = getNowTime();  //    cclOG("endTime=%lld",endTime);  //    cclOG("needTime=%lld",endTime - startTime);            return vec;  }    /**  *  查询数据条数回调  *  *  @return 0  */  int searchDataCountCallback(voID* para,char** column_name) {      int* count = (int*)para;      *count = (int)atof(column_value[0]);      return 0;  }    /**  *  查询记录的条数  *  *  @param sql 查询记录SQL语句  *  *  @return 记录条数  */  int DBUtil::searchDataCount(std::string asql) {            openDBWithname(cDBname);            int count = 0;      char* errMsg = NulL;      int result = sqlite3_exec(m_pDataBase,searchDataCountCallback,&count,&errMsg);      if (result != sqlITE_OK) {          log( "查询记录条数失败,错误码:%d,错误原因:%s\n",errMsg);      }            if (errMsg) {          sqlite3_free(errMsg);          errMsg = NulL;      }            closeDB();            return count;  }    /**  *  开始事务  *  *  @return  *** 作结果(sqlite3提供的宏)  */  int DBUtil::beginTransaction() {      char* errMsg = NulL;      int result = sqlite3_exec(m_pDataBase,"begin transaction",&errMsg);      if (result != sqlITE_OK ){          log("开始事务记录失败,错误码:%d,错误原因:%s\n",errMsg);      }      return result;  }    /**  *  提交事务(失败回滚)  *  *  @param aResult        *** 作结果  *  *  @return  *** 作结果(sqlite3提供的宏)  */  int DBUtil::comitTransaction(int aResult) {      if (aResult == sqlITE_OK) {          char* errMsg = NulL;          int result = sqlite3_exec(m_pDataBase,"commit transaction",&errMsg);          if (result != sqlITE_OK) {              log("提交事务记录失败,错误码:%d,错误原因:%s\n",errMsg);          }          return result;      } else {          char* errMsg = NulL;          int result = sqlite3_exec(m_pDataBase,"rollback transaction",&errMsg);          if (result != sqlITE_OK ) {              log("回滚事务记录失败,错误码:%d,错误原因:%s\n",errMsg);          }          return result;      }  }  

本文由CC原创总结,如需转载请注明出处:http://www.jb51.cc/article/p-spqtwpdw-g.html 总结

以上是内存溢出为你收集整理的Cocos2d-x 分享一个封装的Sqlite3的DBUtil类全部内容,希望文章能够帮你解决Cocos2d-x 分享一个封装的Sqlite3的DBUtil类所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1031085.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存