sqlite3 *pdb=NULL;//创建sqlite指针

    std::string path= FileUtils::getInstance()->getWritablePath()+"save.db";//指定数据库路径

    std::string sql;//需要执行的sql语句

    int result;

    result=sqlite3_open(path.c_str(),&pdb);//打开数据库,如果不存在则创建一个

    if(result!=SQLITE_OK)

    {

        log("open database failed, number%d",result);

    }

 

    sql="create table student(ID integer primary key autoincrement,name text,sex text)";//创建数据库表

    result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);

    if(result!=SQLITE_OK)

        log("create failed");

 

    sql="insert into student values(1,'student1','male')"; //插入数据

    result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);

    if(result!=SQLITE_OK)

        log("insert data failed!");

 

    sql="insert into student values(2,'student2','female')";

    result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);

    if(result!=SQLITE_OK)

        log("insert data failed!");

 

    sql="insert into student values(3,'student3','male')";

    result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);

    if(result!=SQLITE_OK)

        log("insert data failed!");

 

    char **re;//查询结果

    int r,c;//行、列

    sqlite3_get_table(pdb,"select * from student",&re,&r,&c,NULL);//查询

    log("row is %d,column is %d",r,c);

 

    for(int i=1;i<=r;i++)//2

    {

        for(int j=0;j<c;j++)

        {

            log("%s",re[i*c+j]);

        }

    }

 

    sql="delete from student where ID=1";

    result=sqlite3_exec(pdb,sql.c_str(), NULL,NULL,NULL);//删除数据

    if(result!=SQLITE_OK)

        log("delete data failed!");

 

    sqlite3_free_table(re);//释放数据表

    sqlite3_close(pdb);//关闭数据库

    数据操作完成之后,一定要关闭数据库,否侧会造成内存泄漏。

    数据文件存放的位置:

  •     Android

    1

    /data/data/com.youCompany.Helloworld/files/save.db

  •     iOS:

        位于程序沙盒的文档目录下

    1

    ../Documents/save.db