`
zhuangshuo
  • 浏览: 19999 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

cocos2dx sqlite3封装使用

阅读更多
DB.h

/*
 * DB.h
 *
 *  Created on: 2013-6-8
 *      Author: zhuang
 */



#ifndef _DB_H_
#define _DB_H_
#include "cocos2d.h"
// DB
#include "sqlite3.h"

using namespace cocos2d;
using namespace std;

class  DB
{
public:
DB();
     ~DB();

 static DB* sharedDB();

sqlite3 *pDB;//数据库指针
std::string sqlstr;//SQL指令
     char * errMsg;//错误信息
     int results;//sqlite3_exec返回值

bool OpenDBWithFileName(char *dbName);
bool CreateTableWithContent(char *dbExec);
bool IsTableExistedWithTableName(std::string dbExec);
bool GetTableDataWithContent(std::string dbExec);
bool InsertTableDataWithContent(std::string dbExec);
bool DeleteTableDataWithContent(std::string dbExec);
bool UpdateTableDataWithContent(std::string dbExec);
bool ClearTableData(std::string dbExec);
void CloseDB();

void DeleteTable(string sql,string name );



int GetPlayerInfoScores(std::string dbExec);
bool GetPassInfoIsUnlockedWithIndex(std::string dbExec);
int GetPassInfoStartsWithIndex(std::string dbExec);




};
#endif




DB.cpp

#include "DB.h"


DB::DB()
{

//=================DB========================[
        pDB =NULL;//数据库指针
        sqlstr="";//SQL指令
        errMsg = NULL;//错误信息
        results=-1;//sqlite3_exec返回值


}

DB::~DB()
{
}


DB* DB::sharedDB()
{
    static DB sharedDb;
    return &sharedDb;
}


/*
 * //在数据库中判断名为name的表示否存在,如果不存在则创建这张表
//@示例语句string sqls = "create table user(id integer,username text,password text)";
 *
 * //删除表格
//@示例语句sqlstr="drop table name";
 *
 * **/








//====================================================================
//============================ 数据库 ====================================
//====================================================================

//打开一个数据库,如果该数据库不存在,则创建一个数据库文件
/*
 * data.db
 * */
 bool  DB::OpenDBWithFileName(char *dbName)
 {
		bool success=false;
		std::string path = CCFileUtils::sharedFileUtils()->getWritablePath()
					+ dbName;
		int result = sqlite3_open(path.c_str(), &pDB);
		if( result != SQLITE_OK )
		{
		CCLog("SQLITE_OK:%d",SQLITE_OK);
		CCLog( "open db failed ,error :%d ,cause: %s " , result, errMsg );
		success=false;
		}else
		{
		  CCLog( "open db success  ");
		  success=true;
		}

     return success;
 }



//创建表,设置ID为主键,且自动增加
 //create table playerinfo( ID integer primary key autoincrement, playername nvarchar(32),playerscores int )
 bool  DB::CreateTableWithContent(char *dbExec)
 {
 bool success=false;

        int result=sqlite3_exec( pDB, dbExec , NULL, NULL, &errMsg );
        if( result != SQLITE_OK )
{
CCLog( "create table failed ,error :%d ,cause: %s " , result, errMsg );
success=false;
}
else
{
  CCLog( "create table success  ");
  success=true;
}

return success;
 }


//判断表是否存在

 bool  DB::IsTableExistedWithTableName(std::string dbExec)
 {
 bool success=false;

std::string dbExecs="";
dbExecs.append("select count(type) from sqlite_master where type='table' and name='");
dbExecs.append(dbExec);
dbExecs.append("'");

int result=sqlite3_exec( pDB, dbExecs.c_str() , NULL, NULL, &errMsg );
        if( result != SQLITE_OK )
{
CCLog( "table not exist ");
success=false;
}
else
{
  CCLog( "table  is  existed ");
  success=true;
}

return success;
 }
 int isExisted( void * para, int n_column, char ** column_value, char ** column_name )
 {
bool *isExisted_=(bool*)para;
*isExisted_=(**column_value)!='0';
return 0;
 }


// 获取数据
bool DB::GetTableDataWithContent(std::string dbExec)
{
bool success=false;

        int result = sqlite3_exec( pDB, dbExec.c_str() , NULL, NULL, &errMsg ); //   loadRecord
        if(result != SQLITE_OK )
{
CCLog( "get GetTableDataWithContent failed,error :%d ,cause:%s " , result, errMsg );
success=false;
}
else
{
CCLog( "get GetTableDataWithContent success ");
success=true;
}

return success;
}


//插入数据
//insert into playerinfo( playername,playerscores  ) values ( '忘川之水', 683500 )
bool DB::InsertTableDataWithContent(std::string dbExec)
{
bool success=false;

        int result = sqlite3_exec( pDB, dbExec.c_str() , NULL, NULL, &errMsg );
        if(result != SQLITE_OK )
{
CCLog( "insert failed,error :%d ,cause:%s " , result, errMsg );
success=false;
}
else
{
CCLog( "insert success  ");
success=true;
}

return success;
}

//删除数据  delete from playerinfo where playername = 'default2'
bool DB::DeleteTableDataWithContent(std::string dbExec)
{
bool success=false;

        int result = sqlite3_exec( pDB, dbExec.c_str() , NULL, NULL, &errMsg );
        if(result != SQLITE_OK )
{
CCLog( "delete failed,error :%d ,cause:%s " , result, errMsg );
success=false;
}
else
{
CCLog( "delete success  ");
success=true;
}

return success;
}



//更新数据   update gamepass set passisunlocked=1  where passindex = 2
bool DB::UpdateTableDataWithContent(std::string dbExec)
{
bool success=false;

        int result = sqlite3_exec( pDB, dbExec.c_str() , NULL, NULL, &errMsg );
        if(result != SQLITE_OK )
{
CCLog( "update failed,error :%d ,cause:%s " , result, errMsg );
success=false;
}
else
{
CCLog( "update success ");
success=true;
}

return success;
}

// 清空数据
bool DB::ClearTableData(std::string dbExec)
{
 bool success=false;

std::string dbExecs="";
dbExecs.append("delete from  ");
dbExecs.append(dbExec);
dbExecs.append(" ");

        int result = sqlite3_exec( pDB, dbExecs.c_str() , NULL, NULL, &errMsg );
        if(result != SQLITE_OK )
{
CCLog( "clear failed,error:%d ,cause :%s " , result, errMsg );
success=false;
}
else
{
CCLog( " clear db success   ");
success=true;
}

return success;
}

//关闭数据库
void DB::CloseDB()
{
        sqlite3_close(pDB);
}


//=================================================
int DB::GetPlayerInfoScores(std::string dbExec)
{
bool success=false;
int scores=0;

   sqlite3_stmt *statement=NULL;
int result =  sqlite3_prepare(pDB, dbExec.c_str() , dbExec.length(), &statement, 0);
        if(result != SQLITE_OK )
{
CCLog( "get GetPlayerInfo failed,error :%d ,cause:%s " , result, errMsg );
success=false;
}
else
{
CCLog( "get GetPlayerInfo success  ");
success=true;

while(sqlite3_step(statement) == SQLITE_ROW)
{
scores=sqlite3_column_int(statement, 2);
 };

}

return scores;
}

bool DB::GetPassInfoIsUnlockedWithIndex(std::string dbExec)
{
bool success=false;
bool isUnlocked=false;

   sqlite3_stmt *statement=NULL;
int result =  sqlite3_prepare(pDB, dbExec.c_str() , dbExec.length(), &statement, 0);
        if(result != SQLITE_OK )
{
CCLog( "get GetPlayerInfo failed,error :%d ,cause:%s " , result, errMsg );
success=false;
}
else
{
CCLog( "get GetPlayerInfo success  ");
success=true;

while(sqlite3_step(statement) == SQLITE_ROW)
{
(sqlite3_column_int(statement, 3)==1)?(isUnlocked=true):(isUnlocked=false);
 };

}

return isUnlocked;
}

//select *  from  gamepass  where passindex =2
int DB::GetPassInfoStartsWithIndex(std::string dbExec)
{
bool success=false;
int starts=0;

   sqlite3_stmt *statement=NULL;
int result =  sqlite3_prepare(pDB, dbExec.c_str() , dbExec.length(), &statement, 0);
        if(result != SQLITE_OK )
{
CCLog( "get GetPlayerInfo failed,error :%d ,cause:%s " , result, errMsg );
success=false;
}
else
{
CCLog( "get GetPlayerInfo success  ");
success=true;

while(sqlite3_step(statement) == SQLITE_ROW)
{
starts=sqlite3_column_int(statement, 3);
 };

}

return starts;
}

//@示例语句sqlstr="drop table name";
void DB::DeleteTable(string sql,string name){

	if (IsTableExistedWithTableName(name))
	    {
	        int result = sqlite3_exec(pDB,sql.c_str(),NULL,NULL,&errMsg);
	        if( result != SQLITE_OK )
	            CCLog( "创建表失败,错误码:%d ,错误原因:%s\n" , result, errMsg );
	    }
}



test

#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "DB.h"

using namespace cocos2d;
using namespace CocosDenshion;

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
this->db();
    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(HelloWorld::menuCloseCallback) );
    pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition( CCPointZero );
    this->addChild(pMenu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Thonburi", 34);

    // ask director the window size
    CCSize size = CCDirector::sharedDirector()->getWinSize();

    // position the label on the center of the screen
    pLabel->setPosition( ccp(size.width / 2, size.height - 20) );

    // add the label as a child to this layer
    this->addChild(pLabel, 1);

    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    pSprite->setPosition( ccp(size.width/2, size.height/2) );

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);
    
    return true;
}

void HelloWorld::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}

void HelloWorld::db(){
	 // DB test
	if(DB::sharedDB()->OpenDBWithFileName("save.db")) //打开一个数据库,如果该数据库不存在,则创建一个数据库文件
	{
	              //创建表,设置ID为主键,且自动增加    ———— OK
	    DB::sharedDB()->CreateTableWithContent("create table playerinfo( ID integer primary key autoincrement, playername nvarchar(32),playerscores int ) ");
	    DB::sharedDB()->CreateTableWithContent("create table gamepass( ID integer primary key autoincrement, passindex int, passstarts int ,passisunlocked int  ) ");

	              //插入数据        ———— OK
	    DB::sharedDB()->InsertTableDataWithContent(" insert into playerinfo( playername,playerscores  ) values ( '北京', 683500 ) ");
	    DB::sharedDB()->InsertTableDataWithContent(" insert into playerinfo( playername,playerscores ) values ( '上海', 445555 ) ");
	    DB::sharedDB()->InsertTableDataWithContent(" insert into playerinfo( playername,playerscores ) values ( '深圳', 8556548 ) ");

	    DB::sharedDB()->InsertTableDataWithContent(" insert into gamepass( passindex,passstarts,passisunlocked ) values ( 1, 2, 1 ) ");
	    DB::sharedDB()->InsertTableDataWithContent(" insert into gamepass( passindex,passstarts,passisunlocked ) values ( 2, 3, 0 ) ");
	    DB::sharedDB()->InsertTableDataWithContent(" insert into gamepass( passindex,passstarts,passisunlocked ) values ( 3, 0, 0 ) ");

	// 获取数据   ———— OK
	   int scores=DB::sharedDB()->GetPlayerInfoScores(" select *  from  playerinfo  where  playername ='default' ");
	   int starts=DB::sharedDB()->GetPassInfoStartsWithIndex(" select *  from  gamepass  where passindex =2 ");
	bool isLocked1=DB::sharedDB()->GetPassInfoIsUnlockedWithIndex(" select *  from  gamepass  where  passindex =1 ");
	bool isLocked3=DB::sharedDB()->GetPassInfoIsUnlockedWithIndex(" select *  from  gamepass  where  passindex =3 ");
	CCLog("= %d =",scores);
	CCLog("= %d =",starts);
	(isLocked1==true)?( CCLog("= has unlock =")):(CCLog("= is locked ="));
	(isLocked3==true)?( CCLog("= has unlock =")):(CCLog("= is locked ="));


	DB::sharedDB()->DeleteTable("drop table gamepass","gamepass");
	// 删除数据     ———— OK
	//DB::sharedDB()->DeleteTableDataWithContent("delete from playerinfo where playername = 'default2' ");

	// 更新数据    ———— OK
	//DB::sharedDB()->UpdateTableDataWithContent("update gamepass set passisunlocked=1  where passindex = 2 ");


	              //关闭数据库     ———— OK
	    DB::sharedDB()->CloseDB();
	}
}



参考:http://blog.csdn.net/ym19860303/article/details/8531998
      http://blog.sina.com.cn/s/blog_6b154dd301012ann.html
分享到:
评论

相关推荐

    cocos2d-x封装的sqlite3开源库

    cocos2d-x封装的sqlite3开源库,简便很多

    SQLite3 数据库 cocos2d封装类

    SQLite3数据库 Helpe封装类,对刚学习和不懂得人有帮助。希望大家使用流程!

    Cocos2d-x实战:JS卷——Cocos2d-JS开发

    资源名称:Cocos2d-x实战:JS卷——Cocos2d-JS开发内容简介:本书是介绍Cocos2d-x游戏编程和开发技术书籍,介绍了使用Cocos2d-JS中核心类、瓦片地图、物理引擎、音乐音效、数据持久化、网络通信、性能优化、多平台...

    cocos2d入门cocos2d入门

    cocos2d入门 cocos2d入门 cocos2d入门 cocos2d入门 cocos2d入门 cocos2d入门

    cocos2d-x json字符串与cocos2d::Value转换工具

    该资源主要用于cocos2d-x中Value与json字符串的相互转换,提供从json文件...json字符串转换成cocos::Value后就可以很方便的使用了,其本质就是json字符串的数组对应cocos2d::ValueVector,对象对应cocos2d::ValueMap.

    Cocos2d-JS中使用Cocos Studio资源03:设置界面

    Cocos2d-JS中使用Cocos Studio资源03:设置界面

    cocos2d-x-2.1.5

    cocos2d-x-2.1.5

    cocos2d-x事件类

    在使用cocos2d-x开发游戏的过程中,为了实现逻辑和显示相分离。 在下通宵了一个晚上,写出了该事件类。 谨记,该事件只能用于cocos2d-x中。 事件发送者需要继承EventDispatcher类 事件接收者需要继承EventHandle类...

    cocos2d游戏资源

    Cocos2d-x 通过封装底层图形接口提供了易用的API,降低了游戏开发的门槛,让使用者可以专注于开发游戏,而不用关注底层的技术细节。更重要的是 Cocos2d-x 是一个完全开源的游戏引擎,这就允许您在游戏开发过程中根据...

    cocos2d-x3D扩展3DToolKitforcocos2d-x.zip

    2,在cocos2d-x-2.2目录下新建一个文件夹myProject,再在myProject下建一个文件夹3DToolKitDemo。 3,git下来的HelloCpp文件夹放到3DToolKitDemo文件夹中。 4,编译运行HelloCpp中的ios工程。 二,Win32 (IDE:...

    Cocos2D权威指南

    第1章 开始前的准备工作 1 第2章 你的第一款iPhone游戏:垂直射击游戏 38 第3章 Cocos2D核心类 69 第4章 Cocos2D中的动作、特效与动画 152 第5章 Cocos2D中的文本渲染系统 229 共19章

    Cocos2d-x 3.x游戏开发实战pdf含目录

    Cocos2d-x 3.x游戏开发实战pdf含目录,内容详细,强烈推荐给大家。

    教你用Cocos2D-X开发跨平台移动应用

    Cocos2d-x源于Cocos2d,是一款开源游戏引擎项目,是一款基于对原有iOS平台cocos2d重写为C++的开源代码,封装了OpenGL,Box2d,LibCurl,LibPng等开源的跨平台代码。由于基于C++和STL特点使其广泛应用于游戏开发、移动...

    cocos2d初级教程-Cocos2d SimpleGame源码

    Ray Wenderlich的《Cocos2d SimpleGame》,被认为是cocos2d的初学者最好的教程,这本书被Cocos2D-X团队从objective-c转化到了c++版,并发布在了github上。在此感谢Ray Wenderlich的慷慨相助。 源代码是在cocos2d-x ...

    别踩白块游戏cocos2d-x3.x实现

    别踩白块游戏cocos2d-x3.x实现

    cocos2d-x游戏代码

    cocos2d-x游戏代码

    cocos2d-x实战项目

    cocos2d-x实战项目 01.cocos2d-x原理及环境配置.rar 03.cocostudio使用方法及UI控制.rar 04.XML文件读取与骨骼动画.rarcocos2d-x实战项目 01.cocos2d-x原理及环境配置.rar 03.cocostudio使用方法及UI控制.rar 04.XML...

    Cocos2d-x 如何使用Lua脚本

    Cocos2d-x中使用Lua脚本的初步使用,在Cocos2d-x中访问Lua脚本中的变量

    cocos2d粒子编辑器 particle_builder -windows

    windows环境,一款很好用cocos2d粒子特效编辑器,里面有不少例子

    Cocos2d-x实战 JS卷 Cocos2d-JS开发

    Cocos2d-x实战 JS卷 Cocos2d-JS开发 PDF 电子书完整版本

Global site tag (gtag.js) - Google Analytics