iOS 資料庫持久化,ios資料庫
Java代碼
- -(void) addObserver{
- //當程式進入後台時執行操作
- UIApplication *app = [UIApplication sharedApplication];
- [[ NSNotificationCenter defaultCenter] addObserver: self
- selector:@selector(appwillresignActive) name:UIApplicationWillResignActiveNotification object:app];
- }
- -(void) appwillresignActive{
- NSLog(@"監聽測試");
- }
-(void) addObserver{
//當程式進入後台時執行操作
UIApplication *app = [UIApplication sharedApplication];
[[ NSNotificationCenter defaultCenter] addObserver: self
selector:@selector(appwillresignActive) name:UIApplicationWillResignActiveNotification object:app];
}
-(void) appwillresignActive{
NSLog(@"監聽測試");
}
頭部引入
Java代碼
- #import "sqlite3.h"
#import "sqlite3.h"
Java代碼
- -(void) makeDBinfo{
- NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
-
- NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"mydb"];
-
- char *errorMsg;
-
- //開啟或建立資料庫
- sqlite3 *database;
-
- if (sqlite3_open([databaseFilePath UTF8String], &database)!=SQLITE_OK) {
- sqlite3_close(database);
- }else {
- NSLog(@"open sqlite db ok.");
- }
- //建立資料庫表
-
- const char *createSql=" create table if not exists persons (id integer primary key autoincrement,name text)";
-
- if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK)
- {
- NSLog(@"create table ok.");
- }else
- {
- //如果在多個地方使用errorMsg,那麼每次使用完畢要清空一下字串,比如這樣:
- NSLog(@"error: %s",errorMsg);
- sqlite3_free(errorMsg);
- }
- // 向表中插入記錄
- const char *insertSql="insert into persons (name) values(\"張三\")";
- if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK)
- {
- NSLog(@"insert ok.");
- }else
- {
- //如果在多個地方使用errorMsg,那麼每次使用完畢要清空一下字串,比如這樣:
- NSLog(@"error: %s",errorMsg);
- sqlite3_free(errorMsg);
- }
-
- //結果集的查詢,需要用到statement:
- const char *selectSql="select id,name from persons where name = ? ";
- sqlite3_stmt *statement;
-
- if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil)==SQLITE_OK) {
- NSLog(@"select ok.");
-
- sqlite3_bind_text(statement, 1, "張三",-1,NULL);
-
-
- while (sqlite3_step(statement)==SQLITE_ROW) {
- int _id=sqlite3_column_int(statement, 0);
- NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];
- NSLog(@"row>>id %i, name %@",_id,name);
- }
-
- sqlite3_finalize(statement);
- }
- sqlite3_close(database);
-
- }
-(void) makeDBinfo{
NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"mydb"];
char *errorMsg;
//開啟或建立資料庫
sqlite3 *database;
if (sqlite3_open([databaseFilePath UTF8String], &database)!=SQLITE_OK) {
sqlite3_close(database);
}else {
NSLog(@"open sqlite db ok.");
}
//建立資料庫表
const char *createSql=" create table if not exists persons (id integer primary key autoincrement,name text)";
if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK)
{
NSLog(@"create table ok.");
}else
{
//如果在多個地方使用errorMsg,那麼每次使用完畢要清空一下字串,比如這樣:
NSLog(@"error: %s",errorMsg);
sqlite3_free(errorMsg);
}
// 向表中插入記錄
const char *insertSql="insert into persons (name) values(\"張三\")";
if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK)
{
NSLog(@"insert ok.");
}else
{
//如果在多個地方使用errorMsg,那麼每次使用完畢要清空一下字串,比如這樣:
NSLog(@"error: %s",errorMsg);
sqlite3_free(errorMsg);
}
//結果集的查詢,需要用到statement:
const char *selectSql="select id,name from persons where name = ? ";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil)==SQLITE_OK) {
NSLog(@"select ok.");
sqlite3_bind_text(statement, 1, "張三",-1,NULL);
while (sqlite3_step(statement)==SQLITE_ROW) {
int _id=sqlite3_column_int(statement, 0);
NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];
NSLog(@"row>>id %i, name %@",_id,name);
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
刪除表操作
constchar *sql_drop_table="drop table if exists t";
constchar *sql_create_table="create table t(id int primary key,msg varchar(128))";
sqlite3_exec(db,sql_drop_table,0,0,&errmsg);
sqlite3_exec(db,sql_create_table,0,0,&errmsg);
插入資料
sqlite3_exec(db,"insert into t(id,msg) values(1,'Ady Liu')",NULL,NULL,&errmsg);
先行編譯操作
int i = 0;
sqlite3_stmt *stmt;
char ca[255];
//prepare statement
sqlite3_prepare_v2(db,"insert into t(id,msg) values(?,?)",-1,&stmt,0);
for(i=10;i<20;i++){
sprintf(ca,"HELLO#%i",i);
sqlite3_bind_int(stmt,1,i);
sqlite3_bind_text(stmt,2,ca,strlen(ca),NULL);
sqlite3_step(stmt);
sqlite3_reset(stmt);
}
sqlite3_finalize(stmt)
先行編譯操作比較麻煩的,完整的先行編譯操作的流程是:
通過sqlite3_prepare_v2()建立一個sqlite3_stmt對象
通過sqlite3_bind_*()綁定先行編譯欄位的值
通過sqlite3_step()執行SQL語句
通過sqlite3_reset()重設先行編譯語句,重複操作2多次
通過sqlite3_finalize()銷毀資源
先行編譯SQL語句中可以包含如下幾種形式:
?
?NNN
:VVV
@VVV
$VVV
NNN代表數字,VVV代表字串。
如果是?或者?NNN,那麼可以直接sqlite3_bind_*()進行操作,如果是字串,還需要通過sqlite3_bind_parameter_index()擷取對應的index,然後再調用sqlite3_bind_*()操作。這通常用於構造不定條件的SQL語句(動態SQL語句)。
查詢操作
寫道
回呼函數的解釋參考最上面的描述。 首先聲明一個回呼函數。
int print_record(void *,int,char **,char **);
查詢代碼
//select data
ret = sqlite3_exec(db,"select * from t",print_record,NULL,&errmsg);
if(ret != SQLITE_OK){
fprintf(stderr,"query SQL error: %s\n",errmsg);
}
現在定義回呼函數,只是簡單的輸出欄位值。
int print_record(void *params,int n_column,char **column_value,char **column_name){
int i;
for(i=0;i<n_column;i++){
printf("\t%s",column_value[i]);
}
printf("\n");
return 0;
}
不使用回調的查詢操作
寫道
定義使用的變數
char **dbresult; int j,nrow,ncolumn,index;
查詢操作
//select table
ret = sqlite3_get_table(db,"select * from t",&dbresult,&nrow,&ncolumn,&errmsg);
if(ret == SQLITE_OK){
printf("query %i records.\n",nrow);
index=ncolumn;
for(i=0;i<nrow;i++){
printf("[%2i]",i);
for(j=0;j<ncolumn;j++){
printf(" %s",dbresult[index]);
index++;
}
printf("\n");
}
}
sqlite3_free_table(dbresult);
受影響的記錄數
我們可以使用sqlite3_change(sqlite3 *)的API來統計上一次操作受影響的記錄數。
ret = sqlite3_exec(db,"delete from t",NULL,NULL,&errmsg);
if(ret == SQLITE_OK){
printf("delete records: %i\n",sqlite3_changes(db));
}
總結
寫道
這裡我們接觸了SQLITE3的13個API:
sqlite3_open()
sqlite3_exec()
sqlite3_close()
sqlite3_prepare_v2
sqlite3_bind_*()
sqlite3_bind_parameter_index()
sqlite3_step()
sqlite3_reset()
sqlite3_finalize()
sqlite3_get_table
sqlite3_change()
sqlite3_free()
sqlite3_free_table()
事實上截止到SQLITE3.7.14(2012/09/03) 一共提供了204個API函數(http://www.sqlite.org/c3ref/funclist.html)。
但最精簡的API函數大概有6個:
sqlite3_open()
sqlite3_prepare()
sqlite3_step()
sqlite3_column()
sqlite3_finalize()
sqlite3_close()
核心API也就10個(在精簡API基礎上增加4個):
sqlite3_exec()
sqlite3_get_table()
sqlite3_reset()
sqlite3_bind()
因此掌握起來還是比較容易的。