本文转自:http://4137613.blog.51cto.com/4127613/772518
#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; }
sqlstr="select count(*) from MyTable_1 where ID = 2";
sqlite3_exec( pDB, sqlstr.c_str() , isExisted, &isExisted_, &errMsg );
sqlstr="select * from MyTable_1";
sqlite3_exec( pDB, sqlstr.c_str() , loadRecordCount, &count, &errMsg );
{
int *count=(int*)para;
*count=n_column;
return 0;
}
sqlite3_exec( pDB, sqlstr.c_str() , loadRecord, NULL, &errMsg );
{
CCLog("ID=%s,name=%s",column_value[0],column_value[1]);
return 0;
}
本文出自 “老G的小屋” 博客,请务必保留此出处http://4137613.blog.51cto.com/4127613/772518