本文共 3835 字,大约阅读时间需要 12 分钟。
cocos2d-x学习笔记17:记录存储2:SQLite基本使用
#include "sqlite3.h"
sqlite3 *pDB = NULL;//数据库指针 char * errMsg = NULL;//错误信息 std::string sqlstr;//SQL指令 int result;//sqlite3_exec返回值 //打开一个数据库,如果该数据库不存在,则创建一个数据库文件 result = sqlite3_open("save.db", &pDB); if( result != SQLITE_OK ) CCLog( "打开数据库失败,错误码:%d ,错误原因:%s\n" , result, errMsg ); //创建表,设置ID为主键,且自动增加 result=sqlite3_exec( pDB, "create table MyTable_1( ID integer primary key autoincrement, name nvarchar(32) ) " , NULL, NULL, &errMsg ); if( result != SQLITE_OK ) CCLog( "创建表失败,错误码:%d ,错误原因:%s\n" , result, errMsg ); //插入数据 sqlstr=" insert into MyTable_1( name ) values ( '克塞' ) "; result = sqlite3_exec( pDB, sqlstr.c_str() , NULL, NULL, &errMsg ); if(result != SQLITE_OK ) CCLog( "插入记录失败,错误码:%d ,错误原因:%s\n" , result, errMsg ); //插入数据 sqlstr=" insert into MyTable_1( name ) values ( '葫芦娃' ) "; result = sqlite3_exec( pDB, sqlstr.c_str() , NULL, NULL, &errMsg ); if(result != SQLITE_OK ) CCLog( "插入记录失败,错误码:%d ,错误原因:%s\n" , result, errMsg ); //插入数据 sqlstr=" insert into MyTable_1( name ) values ( '擎天柱' ) "; result = sqlite3_exec( pDB, sqlstr.c_str() , NULL, NULL, &errMsg ); if(result != SQLITE_OK ) CCLog( "插入记录失败,错误码:%d ,错误原因:%s\n" , result, errMsg ); //关闭数据库 sqlite3_close(pDB);
sqlstr="update MyTable_1 set name='威震天' where ID = 3"; sqlite3_exec( pDB, sqlstr.c_str() , NULL, NULL, &errMsg );
sqlstr="delete from MyTable_1 where ID = 2"; sqlite3_exec( pDB, sqlstr.c_str() , NULL, NULL, &errMsg );
bool isExisted_; sqlstr="select count(type) from sqlite_master where type='table' and name='MyTable_1'"; sqlite3_exec( pDB, sqlstr.c_str() , isExisted, &isExisted_, &errMsg );
int isExisted( void * para, int n_column, char ** column_value, char ** column_name ) { bool *isExisted_=(bool*)para; *isExisted_=(**column_value)!='0'; return 0; }
bool isExisted_; sqlstr="select count(*) from MyTable_1 where ID = 2"; sqlite3_exec( pDB, sqlstr.c_str() , isExisted, &isExisted_, &errMsg );
int count; sqlstr="select * from MyTable_1"; sqlite3_exec( pDB, sqlstr.c_str() , loadRecordCount, &count, &errMsg );
int loadRecordCount( void * para, int n_column, char ** column_value, char ** column_name ) { int *count=(int*)para; *count=n_column; return 0; }
sqlstr="select * from MyTable_1 where ID=3"; sqlite3_exec( pDB, sqlstr.c_str() , loadRecord, NULL, &errMsg );
int loadRecord( void * para, int n_column, char ** column_value, char ** column_name ) { CCLog("ID=%s,name=%s",column_value[0],column_value[1]); return 0; }
转载地址:http://dsosi.baihongyu.com/