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

来源:互联网 发布:淘宝免费赠品网 编辑:程序博客网 时间:2024/04/29 20:09
 

      简单的数据可以使用文件方式存储,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,&errMsg);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
 

原创粉丝点击