cocos2d-x學習筆記17:記錄存儲2:SQLite基本使用
然後在init函數中編寫代碼
- #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;
- }
回調函數isExisted的定義,在3)已給出,不再贅述。
- 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 );
6)讀取一條記錄 讀取表MyTable_1中ID=3的記錄,並打印
- 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;
- }
本文出自 “老G的小屋” 博客,請務必保留此出處http://4137613.blog.51cto.com/4127613/772518