Cocos2d-x笔记(二)Sqlite数据库基本操作

 

      简单的数据可以使用文件方式存储,CCUserDefault、CCFileUtil等类都可以完成文件的存储。如数据量比较大、或涉及增删改比较多,就需要考虑使用数据库。以前一直做

android开发,一想到数据库肯定是Sqlite。

          Sqlite数据库本身就是C语言编写的,官方也已经提供了Sqlite的API,这样工作就轻松多了。

1.先到Sqlite官网上下载源码http://www.sqlite.org/sqlite-amalgamation-3071000.zip  ,主要使用的事sqlite3.h和sqlite3.c两个文件。

2.将下载的文件添加到项目中,这里有两种办法,一种是直接拷贝到Classes目录下。另一种这是通过添加附加目录(右键点项目-》属性-》配置属性-》C++-》常规-》附加包含目录)。然后右键点项目-》添加-》现有项,选择那四个源代码文件。

3.接下来就是编写代码了:

    添加一条数据

	sqlite3 *pDB = NULL;
	char *errMsg = NULL;
	std::string sqlStr;
	int result = -1;
	/**
	*在windows上可以使用
	std::string path="test.db";
	数据库文件就保存resource文件夹下
	在android中需要使用
	std::string path=CCFileUtils::sharedFileUtils()->getWritablePath()+"test.db";
	如果不设置路径,会报unable to open the database file
	*/
	std::string path=CCFileUtils::sharedFileUtils()->getWritablePath()+"test.db";  

	result = sqlite3_open(path.c_str(),&pDB);
	if(result != SQLITE_OK)
		CCLog("open database failed ,error code:%d,error reason:%s\n",result,errMsg);
	result = sqlite3_exec(pDB,"create table TestTable(id integer primary key autoincrement,name nvchar(32))",NULL,NULL,&er	rMsg);
	if(result != SQLITE_OK){
		CCLog("create database table failed,error code:%d,error reason:%s",result,errMsg);
	}

	sqlStr = "insert into TestTable( name ) values('zhangsan')";
	result = sqlite3_exec(pDB,sqlStr.c_str(),NULL,NULL,&errMsg);
	if(result != SQLITE_OK){
		CCLog("insert into table failed,error code:%d,error reason:%s\n",result,errMsg);
		fflush(stdout);
	}


      删除数据

sqlstr="delete from TestTable where ID = 2"; 
sqlite3_exec( pDB, sqlstr.c_str() , NULL, NULL, &errMsg ); 

 
    更新数据

sqlstr="update TestTble set name='lishi' where ID = 3"; 
sqlite3_exec( pDB, sqlstr.c_str() , NULL, NULL, &errMsg );

    判断表是否存在

sqlstr="select count(type) from sqlite_master where type='table' and name='TestTable'"; 
sqlite3_exec( pDB, sqlstr.c_str() , isExisted, &isExisted_, &errMsg ); 

    其中isExited是一个回调函数

int isExited( void * para, int n_column, char ** column_value, char ** column_name ) 
{ 
            boolean *isExited=(boolean*)para;  
            return 0; 
} 


 如果想在windows 查看数据库中的内容,可以使用Sqlite管理工具sqlitebrowser,下载地址:http://sourceforge.net/projects/sqlitebrowser/files/latest/download?source=files
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值