IOS嵌入式數據庫SQLite3使用簡析

1.    Sqlite3數據類型及存儲類

    每個存放在sqlite數據庫中(或者由這個數據庫引擎操作)的值都有下面中的一個存儲類:

   (1)NULL,值是NULL

    (2)INTEGER,值是有符號整形,根據值的大小以1,2,3,4,6或8字節存放

   (3)REAL,值是浮點型值,以8字節IEEE浮點數存放

   (4)TEXT,值是文本字符串,使用數據庫編碼(UTF-8,UTF-16BE或者UTF-16LE)存放

   (5)BLOB,只是一個數據塊,完全按照輸入存放(即沒有準換)

    注:①Sqlite沒有單獨的布爾存儲類型,它使用INTEGER作爲存儲類 型,0爲false,1爲true

        ②Sqlite沒有另外爲存儲日期和時間設定一個存儲類集,內置的sqlite日期和時間函數能夠將日期和時間以TEXT,REAL或INTEGER形式存放

      TEXT 作爲IS08601字符串("YYYY-MM-DD HH:MM:SS.SSS")
      REAL 從格林威治時間11月24日,4174 B.C中午以來的天數
      INTEGER 從 1970-01-01 00:00:00 UTC以來的秒數

2.    Sqlite3函數功能簡介

   1)基本函數及結構體

     sqlite3        *pdb  //數據庫句柄,跟文件句柄FILE很類似
     sqlite3_stmt  *stmt  //這個相當於ODBC的Command對象,用於保存編譯好的SQL語句
     sqlite3_open()       //打開數據庫
     sqlite3_exec()       //執行非查詢的sql語句
     sqlite3_prepare()    //準備sql語句,執行select語句或者要使用parameter bind時 ,                             用這個函數(封裝了sqlite3_exec).
     sqlite3_step()       //在調用sqlite3_prepare後,使用這個函數在記錄集中移動。
     sqlite3_close()      //關閉數據庫文件

    2)綁定函數

        int sqlite3_bind_null(sqlite3_stmt*, int);
         int sqlite3_bind_int(sqlite3_stmt*, int, int);
         int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
         int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));

    3)取值函數
     sqlite3_column_text(), 取text類型的數據
     sqlite3_column_blob(),取blob類型的數據
     sqlite3_column_int(), 取int類型的數據

3.    Sqlite3使用步驟

    1) 首先獲取iPhone上Sqlite 3 的數據庫文件的地址
    2) 打開Sqlite 3 的數據庫文件
    3) 定義SQL文
    4) 邦定執行SQL所需要的參數
    5) 執行SQL文,並獲取結果
    6) 釋放資源
    7) 關閉Sqlite 3 數據庫。

4.    Sqlite3數據操作

由於整個例子代碼比較繁瑣,這裏只列出數據庫操作的部分代碼作爲參考:

1.添加開發包libsqlite3.0.dylib

首先是設置項目文件,在項目中添加iPhone版的sqlite3的數據庫的開發包,在項目下的Frameworks點擊右鍵,然後選擇libsqlite3.0.dylib文件。

libsqlite3.0.dylib文件地址:

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/usr/lib/libsqlite3.0.dylib

2.獲取sqlite3的數據庫文件地址:

  1. //數據庫路徑 
  2. -(NSString*)databasePath 
  3. {
  4. NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
  5. NSString *pathname = [path objectAtIndex:0]; 
  6. return [pathname stringByAppendingPathComponent:@”database.sqlite3”]; 

3.打開數據庫

  1. - (BOOL)openDatabase 
  2.  
  3.     if (sqlite3_open([[self databasePath] UTF8String],&database) != SQLITE_OK) 
  4.     { 
  5.         sqlite3_close(database); 
  6.         printf("failed to open the database"); 
  7.         return NO;
  8. } else  
  9.     { 
  10.         printf("open the database successfully"); 
  11.         return YES; 
  12.     }
 

4.創建表

  1. //創建TimerTable表 
  2.  
  3. - (BOOL)createTimerTable 
  4.     if ([self openDatabase]==YES)
  5.     { 
  6.         char *erroMsg; 
  7.         NSString *createSQL = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(timerid INTEGER PRIMARY KEY AUTOINCREMENT,time INTEGER,remaintime INTEGER,iconuri BLOB,vibrate INTEGER,status INTEGER,message TEXT)",TableName]; 
  8.         if (sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &erroMsg)!= SQLITE_OK)
  9.         { 
  10.             sqlite3_close(database); 
  11.             printf("create table faild"); 
  12.             return NO; 
  13.         } 
  14.         else 
  15.         { 
  16.             printf("table was created"); 
  17.             return YES; 
  18.         }
  19.     } 
  20.     else 
  21.         return NO;
 

5.添加數據

  1. //添加Timer 
  2.  
  3. - (BOOL)insertTimer:(TimerInfo *)timerInfo 
  4. {   
  5.     bool isOpen=[self openDatabase]; 
  6.     if (isOpen!=YES) 
  7.       return NO; 
  8.     } 
  9.     sqlite3_stmt *statement; 
  10.     static char *insertTimerSql="INSERT INTO TimerTable(time,remaintime,iconuri,vibrate,status,message,type) VALUES (?,?,?,?,?,?)"; 
  11.     if (sqlite3_prepare_v2(database,insertTimerSql,-1,&statement,NULL)!= SQLITE_OK) 
  12.     { 
  13.         NSLog(@"Error:Failed to insert timer"); 
  14.         return NO; 
  15.     } 
  16.     sqlite3_bind_int(statement,1,timerInfo.time);//timerInfo是一個封裝了相關屬性的實體類對象 
  17.     sqlite3_bind_int(statement,2,timerInfo.remainTime); 
  18.     sqlite3_bind_text(statement,3,[timerInfo.iconuri UTF8String],-1,SQLITE_TRANSIENT); 
  19.     sqlite3_bind_int(statement,4,timerInfo.vibrate); 
  20.     sqlite3_bind_int(statement,5,timerInfo.status); 
  21.     sqlite3_bind_text(statement,6,[timerInfo.message UTF8String],-1,SQLITE_TRANSIENT); 
  22.     int success=sqlite3_step(statement); 
  23.     sqlite3_finalize(statement); 
  24.     if(success==SQLITE_ERROR) 
  25.     { 
  26.         NSLog(@"Error:fail to insert into the database with message."); 
  27.         return NO; 
  28.     } 
  29.     NSLog(@"inserted one timer"); 
  30.     return YES; 

6.查詢數據

  1. //查詢數據庫中所有的TimerInfo,返回一個包含所有TimerInfo的可變數組 
  2.  
  3. -(NSMutableArray *)getAllTimers 
  4.     NSMutableArray *arrayTimers=[[NSMutableArray alloc] init]; 
  5.     NSString *queryStr=@"SELECT * FROM TimerTable"; 
  6.     sqlite3_stmt *statement; 
  7.     if (sqlite3_prepare_v2(database, [queryStr UTF8String], -1, &statement, NULL)!=SQLITE_OK) 
  8.     { 
  9.         printf("Failed to get all timers!\n");   
  10.     } 
  11.     else 
  12.     { 
  13.         while (sqlite3_step(statement)==SQLITE_ROW) 
  14.         { 
  15.             TimerInfo *timerInfo=[[TimerInfo alloc] init];
  16.             timerInfo.timerId =sqlite3_column_int(statement,0);
  17.             timerInfo.time =sqlite3_column_int(statement,1); 
  18.             timerInfo.remainTime=sqlite3_column_int(statement,2); 
  19.             timerInfo.vibrate =sqlite3_column_int(statement,4);
  20.             timerInfo.status = sqlite3_column_int(statement,5); 
  21.             char *messageChar=sqlite3_column_text(statement,6);
  22.             if (messageChar==NULL) 
  23.                 timerInfo.message=nil; 
  24.             else 
  25.                 timerInfo.message =[NSString stringWithUTF8String:messageChar]; 
  26.             [arrayTimers addObject:timerInfo]; 
  27.             [timerInfo release]; 
  28.         } 
  29.     } 
  30.     sqlite3_finalize(statement); 
  31.     NSLog(@"arrayTimersCount: %i",[arrayTimers count]);
  32.     return arrayTimers;

    此外,還有數據庫數據的更新及其刪除操作就不再依依列出,它們之間只是執行的SQL文不同,其他部分的代碼較爲類似。

運行效果:(具體頁面控件及事件:略)

   注:由於我自己目前仍是IOS開發的初學者,在這裏只是做下小結,其中難免有說的不對的地方,所以希望大家多多給予指正。

出處:http://hddev.blog.51cto.com/3365350/863169

5.    參考鏈接

    http://hi.baidu.com/nmjd1989/blog/item/de9b0947d6305295b2b7dc01.html

           http://www.cnblogs.com/wengzilin/tag/SQLite3/

           http://www.cnblogs.com/wengzilin/archive/2012/03/27/2419203.html




發佈了15 篇原創文章 · 獲贊 3 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章