cocos2dx sqlite3封装使用

来源:互联网 发布:简述java垃圾回收机制 编辑:程序博客网 时间:2024/05/18 22:13
[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * DB.h 
  3.  * 
  4.  *  Created on: 2013-6-8 
  5.  *      Author: zhuang 
  6.  */  
  7.   
  8.   
  9.   
  10. #ifndef _DB_H_  
  11. #define _DB_H_  
  12. #include "cocos2d.h"  
  13. // DB  
  14. #include "sqlite3.h"  
  15.   
  16. using namespace cocos2d;  
  17. using namespace std;  
  18.   
  19. class  DB  
  20. {  
  21. public:  
  22. DB();  
  23.      ~DB();  
  24.   
  25.  static DB* sharedDB();  
  26.   
  27. sqlite3 *pDB;//数据库指针  
  28. std::string sqlstr;//SQL指令  
  29.      char * errMsg;//错误信息  
  30.      int results;//sqlite3_exec返回值  
  31.   
  32. bool OpenDBWithFileName(char *dbName);  
  33. bool CreateTableWithContent(char *dbExec);  
  34. bool IsTableExistedWithTableName(std::string dbExec);  
  35. bool GetTableDataWithContent(std::string dbExec);  
  36. bool InsertTableDataWithContent(std::string dbExec);  
  37. bool DeleteTableDataWithContent(std::string dbExec);  
  38. bool UpdateTableDataWithContent(std::string dbExec);  
  39. bool ClearTableData(std::string dbExec);  
  40. void CloseDB();  
  41.   
  42. void DeleteTable(string sql,string name );  
  43.   
  44.   
  45.   
  46. int GetPlayerInfoScores(std::string dbExec);  
  47. bool GetPassInfoIsUnlockedWithIndex(std::string dbExec);  
  48. int GetPassInfoStartsWithIndex(std::string dbExec);  
  49.   
  50.   
  51.   
  52.   
  53. };  
  54. #endif  


DB.CPP

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #include "DB.h"  
  2.   
  3.   
  4. DB::DB()  
  5. {  
  6.   
  7. //=================DB========================[  
  8.         pDB =NULL;//数据库指针  
  9.         sqlstr="";//SQL指令  
  10.         errMsg = NULL;//错误信息  
  11.         results=-1;//sqlite3_exec返回值  
  12.   
  13.   
  14. }  
  15.   
  16. DB::~DB()  
  17. {  
  18. }  
  19.   
  20.   
  21. DB* DB::sharedDB()  
  22. {  
  23.     static DB sharedDb;  
  24.     return &sharedDb;  
  25. }  
  26.   
  27.   
  28. /* 
  29.  * //在数据库中判断名为name的表示否存在,如果不存在则创建这张表 
  30. //@示例语句string sqls = "create table user(id integer,username text,password text)"; 
  31.  * 
  32.  * //删除表格 
  33. //@示例语句sqlstr="drop table name"; 
  34.  * 
  35.  * **/  
  36.   
  37.   
  38.   
  39.   
  40.   
  41.   
  42.   
  43.   
  44. //====================================================================  
  45. //============================ 数据库 ====================================  
  46. //====================================================================  
  47.   
  48. //打开一个数据库,如果该数据库不存在,则创建一个数据库文件  
  49. /* 
  50.  * data.db 
  51.  * */  
  52.  bool  DB::OpenDBWithFileName(char *dbName)  
  53.  {  
  54.         bool success=false;  
  55.         std::string path = CCFileUtils::sharedFileUtils()->getWritablePath()  
  56.                     + dbName;  
  57.         int result = sqlite3_open(path.c_str(), &pDB);  
  58.         if( result != SQLITE_OK )  
  59.         {  
  60.         CCLog("SQLITE_OK:%d",SQLITE_OK);  
  61.         CCLog( "open db failed ,error :%d ,cause: %s " , result, errMsg );  
  62.         success=false;  
  63.         }else  
  64.         {  
  65.           CCLog( "open db success  ");  
  66.           success=true;  
  67.         }  
  68.   
  69.      return success;  
  70.  }  
  71.   
  72.   
  73.   
  74. //创建表,设置ID为主键,且自动增加  
  75.  //create table playerinfo( ID integer primary key autoincrement, playername nvarchar(32),playerscores int )  
  76.  bool  DB::CreateTableWithContent(char *dbExec)  
  77.  {  
  78.  bool success=false;  
  79.   
  80.         int result=sqlite3_exec( pDB, dbExec , NULL, NULL, &errMsg );  
  81.         if( result != SQLITE_OK )  
  82. {  
  83. CCLog( "create table failed ,error :%d ,cause: %s " , result, errMsg );  
  84. success=false;  
  85. }  
  86. else  
  87. {  
  88.   CCLog( "create table success  ");  
  89.   success=true;  
  90. }  
  91.   
  92. return success;  
  93.  }  
  94.   
  95.   
  96. //判断表是否存在  
  97.   
  98.  bool  DB::IsTableExistedWithTableName(std::string dbExec)  
  99.  {  
  100.  bool success=false;  
  101.   
  102. std::string dbExecs="";  
  103. dbExecs.append("select count(type) from sqlite_master where type='table' and name='");  
  104. dbExecs.append(dbExec);  
  105. dbExecs.append("'");  
  106.   
  107. int result=sqlite3_exec( pDB, dbExecs.c_str() , NULL, NULL, &errMsg );  
  108.         if( result != SQLITE_OK )  
  109. {  
  110. CCLog( "table not exist ");  
  111. success=false;  
  112. }  
  113. else  
  114. {  
  115.   CCLog( "table  is  existed ");  
  116.   success=true;  
  117. }  
  118.   
  119. return success;  
  120.  }  
  121.  int isExisted( void * para, int n_column, char ** column_value, char ** column_name )  
  122.  {  
  123. bool *isExisted_=(bool*)para;  
  124. *isExisted_=(**column_value)!='0';  
  125. return 0;  
  126.  }  
  127.   
  128.   
  129. // 获取数据  
  130. bool DB::GetTableDataWithContent(std::string dbExec)  
  131. {  
  132. bool success=false;  
  133.   
  134.         int result = sqlite3_exec( pDB, dbExec.c_str() , NULL, NULL, &errMsg ); //   loadRecord  
  135.         if(result != SQLITE_OK )  
  136. {  
  137. CCLog( "get GetTableDataWithContent failed,error :%d ,cause:%s " , result, errMsg );  
  138. success=false;  
  139. }  
  140. else  
  141. {  
  142. CCLog( "get GetTableDataWithContent success ");  
  143. success=true;  
  144. }  
  145.   
  146. return success;  
  147. }  
  148.   
  149.   
  150. //插入数据  
  151. //insert into playerinfo( playername,playerscores  ) values ( '忘川之水', 683500 )  
  152. bool DB::InsertTableDataWithContent(std::string dbExec)  
  153. {  
  154. bool success=false;  
  155.   
  156.         int result = sqlite3_exec( pDB, dbExec.c_str() , NULL, NULL, &errMsg );  
  157.         if(result != SQLITE_OK )  
  158. {  
  159. CCLog( "insert failed,error :%d ,cause:%s " , result, errMsg );  
  160. success=false;  
  161. }  
  162. else  
  163. {  
  164. CCLog( "insert success  ");  
  165. success=true;  
  166. }  
  167.   
  168. return success;  
  169. }  
  170.   
  171. //删除数据  delete from playerinfo where playername = 'default2'  
  172. bool DB::DeleteTableDataWithContent(std::string dbExec)  
  173. {  
  174. bool success=false;  
  175.   
  176.         int result = sqlite3_exec( pDB, dbExec.c_str() , NULL, NULL, &errMsg );  
  177.         if(result != SQLITE_OK )  
  178. {  
  179. CCLog( "delete failed,error :%d ,cause:%s " , result, errMsg );  
  180. success=false;  
  181. }  
  182. else  
  183. {  
  184. CCLog( "delete success  ");  
  185. success=true;  
  186. }  
  187.   
  188. return success;  
  189. }  
  190.   
  191.   
  192.   
  193. //更新数据   update gamepass set passisunlocked=1  where passindex = 2  
  194. bool DB::UpdateTableDataWithContent(std::string dbExec)  
  195. {  
  196. bool success=false;  
  197.   
  198.         int result = sqlite3_exec( pDB, dbExec.c_str() , NULL, NULL, &errMsg );  
  199.         if(result != SQLITE_OK )  
  200. {  
  201. CCLog( "update failed,error :%d ,cause:%s " , result, errMsg );  
  202. success=false;  
  203. }  
  204. else  
  205. {  
  206. CCLog( "update success ");  
  207. success=true;  
  208. }  
  209.   
  210. return success;  
  211. }  
  212.   
  213. // 清空数据  
  214. bool DB::ClearTableData(std::string dbExec)  
  215. {  
  216.  bool success=false;  
  217.   
  218. std::string dbExecs="";  
  219. dbExecs.append("delete from  ");  
  220. dbExecs.append(dbExec);  
  221. dbExecs.append(" ");  
  222.   
  223.         int result = sqlite3_exec( pDB, dbExecs.c_str() , NULL, NULL, &errMsg );  
  224.         if(result != SQLITE_OK )  
  225. {  
  226. CCLog( "clear failed,error:%d ,cause :%s " , result, errMsg );  
  227. success=false;  
  228. }  
  229. else  
  230. {  
  231. CCLog( " clear db success   ");  
  232. success=true;  
  233. }  
  234.   
  235. return success;  
  236. }  
  237.   
  238. //关闭数据库  
  239. void DB::CloseDB()  
  240. {  
  241.         sqlite3_close(pDB);  
  242. }  
  243.   
  244.   
  245. //=================================================  
  246. int DB::GetPlayerInfoScores(std::string dbExec)  
  247. {  
  248. bool success=false;  
  249. int scores=0;  
  250.   
  251.    sqlite3_stmt *statement=NULL;  
  252. int result =  sqlite3_prepare(pDB, dbExec.c_str() , dbExec.length(), &statement, 0);  
  253.         if(result != SQLITE_OK )  
  254. {  
  255. CCLog( "get GetPlayerInfo failed,error :%d ,cause:%s " , result, errMsg );  
  256. success=false;  
  257. }  
  258. else  
  259. {  
  260. CCLog( "get GetPlayerInfo success  ");  
  261. success=true;  
  262.   
  263. while(sqlite3_step(statement) == SQLITE_ROW)  
  264. {  
  265. scores=sqlite3_column_int(statement, 2);  
  266.  };  
  267.   
  268. }  
  269.   
  270. return scores;  
  271. }  
  272.   
  273. bool DB::GetPassInfoIsUnlockedWithIndex(std::string dbExec)  
  274. {  
  275. bool success=false;  
  276. bool isUnlocked=false;  
  277.   
  278.    sqlite3_stmt *statement=NULL;  
  279. int result =  sqlite3_prepare(pDB, dbExec.c_str() , dbExec.length(), &statement, 0);  
  280.         if(result != SQLITE_OK )  
  281. {  
  282. CCLog( "get GetPlayerInfo failed,error :%d ,cause:%s " , result, errMsg );  
  283. success=false;  
  284. }  
  285. else  
  286. {  
  287. CCLog( "get GetPlayerInfo success  ");  
  288. success=true;  
  289.   
  290. while(sqlite3_step(statement) == SQLITE_ROW)  
  291. {  
  292. (sqlite3_column_int(statement, 3)==1)?(isUnlocked=true):(isUnlocked=false);  
  293.  };  
  294.   
  295. }  
  296.   
  297. return isUnlocked;  
  298. }  
  299.   
  300. //select *  from  gamepass  where passindex =2  
  301. int DB::GetPassInfoStartsWithIndex(std::string dbExec)  
  302. {  
  303. bool success=false;  
  304. int starts=0;  
  305.   
  306.    sqlite3_stmt *statement=NULL;  
  307. int result =  sqlite3_prepare(pDB, dbExec.c_str() , dbExec.length(), &statement, 0);  
  308.         if(result != SQLITE_OK )  
  309. {  
  310. CCLog( "get GetPlayerInfo failed,error :%d ,cause:%s " , result, errMsg );  
  311. success=false;  
  312. }  
  313. else  
  314. {  
  315. CCLog( "get GetPlayerInfo success  ");  
  316. success=true;  
  317.   
  318. while(sqlite3_step(statement) == SQLITE_ROW)  
  319. {  
  320. starts=sqlite3_column_int(statement, 3);  
  321.  };  
  322.   
  323. }  
  324.   
  325. return starts;  
  326. }  
  327.   
  328. //@示例语句sqlstr="drop table name";  
  329. void DB::DeleteTable(string sql,string name){  
  330.   
  331.     if (IsTableExistedWithTableName(name))  
  332.         {  
  333.             int result = sqlite3_exec(pDB,sql.c_str(),NULL,NULL,&errMsg);  
  334.             if( result != SQLITE_OK )  
  335.                 CCLog( "创建表失败,错误码:%d ,错误原因:%s\n" , result, errMsg );  
  336.         }  
  337. }  


test 代码

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #include "HelloWorldScene.h"  
  2. #include "SimpleAudioEngine.h"  
  3. #include "DB.h"  
  4.   
  5. using namespace cocos2d;  
  6. using namespace CocosDenshion;  
  7.   
  8. CCScene* HelloWorld::scene()  
  9. {  
  10.     // 'scene' is an autorelease object  
  11.     CCScene *scene = CCScene::create();  
  12.       
  13.     // 'layer' is an autorelease object  
  14.     HelloWorld *layer = HelloWorld::create();  
  15.   
  16.     // add layer as a child to scene  
  17.     scene->addChild(layer);  
  18.   
  19.     // return the scene  
  20.     return scene;  
  21. }  
  22.   
  23. // on "init" you need to initialize your instance  
  24. bool HelloWorld::init()  
  25. {  
  26.     //////////////////////////////  
  27.     // 1. super init first  
  28.     if ( !CCLayer::init() )  
  29.     {  
  30.         return false;  
  31.     }  
  32. this->db();  
  33.     /////////////////////////////  
  34.     // 2. add a menu item with "X" image, which is clicked to quit the program  
  35.     //    you may modify it.  
  36.   
  37.     // add a "close" icon to exit the progress. it's an autorelease object  
  38.     CCMenuItemImage *pCloseItem = CCMenuItemImage::create(  
  39.                                         "CloseNormal.png",  
  40.                                         "CloseSelected.png",  
  41.                                         this,  
  42.                                         menu_selector(HelloWorld::menuCloseCallback) );  
  43.     pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );  
  44.   
  45.     // create menu, it's an autorelease object  
  46.     CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);  
  47.     pMenu->setPosition( CCPointZero );  
  48.     this->addChild(pMenu, 1);  
  49.   
  50.     /////////////////////////////  
  51.     // 3. add your codes below...  
  52.   
  53.     // add a label shows "Hello World"  
  54.     // create and initialize a label  
  55.     CCLabelTTF* pLabel = CCLabelTTF::create("Hello World""Thonburi", 34);  
  56.   
  57.     // ask director the window size  
  58.     CCSize size = CCDirector::sharedDirector()->getWinSize();  
  59.   
  60.     // position the label on the center of the screen  
  61.     pLabel->setPosition( ccp(size.width / 2, size.height - 20) );  
  62.   
  63.     // add the label as a child to this layer  
  64.     this->addChild(pLabel, 1);  
  65.   
  66.     // add "HelloWorld" splash screen"  
  67.     CCSprite* pSprite = CCSprite::create("HelloWorld.png");  
  68.   
  69.     // position the sprite on the center of the screen  
  70.     pSprite->setPosition( ccp(size.width/2, size.height/2) );  
  71.   
  72.     // add the sprite as a child to this layer  
  73.     this->addChild(pSprite, 0);  
  74.       
  75.     return true;  
  76. }  
  77.   
  78. void HelloWorld::menuCloseCallback(CCObject* pSender)  
  79. {  
  80.     CCDirector::sharedDirector()->end();  
  81.   
  82. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)  
  83.     exit(0);  
  84. #endif  
  85. }  
  86.   
  87. void HelloWorld::db(){  
  88.      // DB test  
  89.     if(DB::sharedDB()->OpenDBWithFileName("save.db")) //打开一个数据库,如果该数据库不存在,则创建一个数据库文件  
  90.     {  
  91.                   //创建表,设置ID为主键,且自动增加    ———— OK  
  92.         DB::sharedDB()->CreateTableWithContent("create table playerinfo( ID integer primary key autoincrement, playername nvarchar(32),playerscores int ) ");  
  93.         DB::sharedDB()->CreateTableWithContent("create table gamepass( ID integer primary key autoincrement, passindex int, passstarts int ,passisunlocked int  ) ");  
  94.   
  95.                   //插入数据        ———— OK  
  96.         DB::sharedDB()->InsertTableDataWithContent(" insert into playerinfo( playername,playerscores  ) values ( '北京', 683500 ) ");  
  97.         DB::sharedDB()->InsertTableDataWithContent(" insert into playerinfo( playername,playerscores ) values ( '上海', 445555 ) ");  
  98.         DB::sharedDB()->InsertTableDataWithContent(" insert into playerinfo( playername,playerscores ) values ( '深圳', 8556548 ) ");  
  99.   
  100.         DB::sharedDB()->InsertTableDataWithContent(" insert into gamepass( passindex,passstarts,passisunlocked ) values ( 1, 2, 1 ) ");  
  101.         DB::sharedDB()->InsertTableDataWithContent(" insert into gamepass( passindex,passstarts,passisunlocked ) values ( 2, 3, 0 ) ");  
  102.         DB::sharedDB()->InsertTableDataWithContent(" insert into gamepass( passindex,passstarts,passisunlocked ) values ( 3, 0, 0 ) ");  
  103.   
  104.     // 获取数据   ———— OK  
  105.        int scores=DB::sharedDB()->GetPlayerInfoScores(" select *  from  playerinfo  where  playername ='default' ");  
  106.        int starts=DB::sharedDB()->GetPassInfoStartsWithIndex(" select *  from  gamepass  where passindex =2 ");  
  107.     bool isLocked1=DB::sharedDB()->GetPassInfoIsUnlockedWithIndex(" select *  from  gamepass  where  passindex =1 ");  
  108.     bool isLocked3=DB::sharedDB()->GetPassInfoIsUnlockedWithIndex(" select *  from  gamepass  where  passindex =3 ");  
  109.     CCLog("= %d =",scores);  
  110.     CCLog("= %d =",starts);  
  111.     (isLocked1==true)?( CCLog("= has unlock =")):(CCLog("= is locked ="));  
  112.     (isLocked3==true)?( CCLog("= has unlock =")):(CCLog("= is locked ="));  
  113.   
  114.   
  115.     DB::sharedDB()->DeleteTable("drop table gamepass","gamepass");  
  116.     // 删除数据     ———— OK  
  117.     //DB::sharedDB()->DeleteTableDataWithContent("delete from playerinfo where playername = 'default2' ");  
  118.   
  119.     // 更新数据    ———— OK  
  120.     //DB::sharedDB()->UpdateTableDataWithContent("update gamepass set passisunlocked=1  where passindex = 2 ");  
  121.   
  122.   
  123.                   //关闭数据库     ———— OK  
  124.         DB::sharedDB()->CloseDB();  
  125.     }  
  126. }  

0 0
原创粉丝点击