cocos2dx中的游戏储存-SQLite

来源:互联网 发布:uploadify php 编辑:程序博客网 时间:2024/05/21 07:53

在SQLite官网下载SQLite的源码,将sqlite3.h和sqlite3.c添加到项目目录下的classes中,将sqlite3.dll和sqlite3.lib添加到proj.win32\Debug.win32中

头文件引入:

    #include "sqlite3.h"    #pragma comment(lib, "sqlite3.lib")

主要代码:

    sqlite3 *pdb = NULL;//创建一个数据库指针    std::string path = FileUtils::getInstance()->getWritablePath()+"save.db";//数据库文件路径    std::string sql;    int result = sqlite3_open(path.c_str(),&pdb);//按path的路径打开数据库,如果该数据库不存在,则创建一个数据库文件    if (result!=SQLITE_OK)    {        log("open database failed,number %d",result);//若创建不成功,输出错误信息    }    sql = "create table student(ID integer primary key autoincrement,name text,sex text)";//创建表的sql语句,其中ID为主键    result = sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);//对数据库指针pdb指向的数据库执行sql语句操作    if (result!=SQLITE_OK)    {        log("create table failed!");    }    sql = "insert into student values(1,'student1','male')";//增加表中记录的sql语句    result = sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);//执行sql语句操作    if (result!=SQLITE_OK)    {        log("insert data failed!");    }    sql = "select * from student";//查找表中所有记录的sql语句    char **re;    int r,c;    sqlite3_get_table(pdb,sql.c_str(),&re,&r,&c,NULL);    for (int i=0;i<r;i++)        for(int j=0;j<c;j++)            log("%s",re[(i+1)*c+j]);    sqlite3_free_table(re);//释放查询结果re    sql="delete from student where ID=1";//删除表中ID为1的sql语句    result=sqlite3_exec(pdb,sql.c_str(), NULL,NULL,NULL);//    if(result!=SQLITE_OK)        log("delete data failed!");    sqlite3_close(pdb);//操作完数据库后要执行关闭操作
0 0
原创粉丝点击