天天看點

iOS FMDB 資料庫~詳解 //聯系人:石虎  QQ: 1224614774昵稱:嗡嘛呢叭咪哄

//聯系人:石虎  QQ: 1224614774昵稱:嗡嘛呢叭咪哄

一、簡單說明

1.什麼是FMDB

FMDB是iOS平台的SQLite資料庫架構

FMDB以OC的方式封裝了SQLite的C語言API

2.FMDB的優點

使用起來更加面向對象,省去了很多麻煩、備援的c語言代碼

對比蘋果自帶的Core Data架構,更加輕量級和靈活

提供了多線程安全的資料庫操作方法,有效地防止資料混亂

FMDB PK Sqlite

  • 優點:
    • 對多線程的并發操作進行處理,是以是線程安全的;
    • 以OC的方式封裝了

      SQLite

      的C語言API,使用起來更加的友善;
    • FMDB是輕量級的架構,使用靈活。
  • 缺點:
    • 因為它是OC的語言封裝的,隻能在ios開發的時候使用,是以在實作跨平台操作的時候存在局限性。 

3.FMDB的github位址

https://github.com/ccgus/fmdb

二、核心類

FMDB有三個主要的類

(1)FMDatabase

一個FMDatabase對象就代表一個單獨的SQLite資料庫

用來執行SQL語句

(2)FMResultSet

使用FMDatabase執行查詢後的結果集

(3)FMDatabaseQueue

用于在多線程中執行多個查詢或更新,它是線程安全的

三、打開資料庫

通過指定SQLite資料庫檔案路徑來建立FMDatabase對象

FMDatabase *db = [FMDatabase databaseWithPath:path];

if (![db open]) {

    NSLog(@"資料庫打開失敗!");

}

檔案路徑有三種情況

(1)具體檔案路徑

  如果不存在會自動建立

(2)空字元串@""

  會在臨時目錄建立一個空的資料庫

  當FMDatabase連接配接關閉時,資料庫檔案也被删除

(3)nil

  會建立一個記憶體中臨時資料庫,當FMDatabase連接配接關閉時,資料庫會被銷毀

四、執行更新

在FMDB中,除查詢以外的所有操作,都稱為“更新”

create、drop、insert、update、delete等

使用executeUpdate:方法執行更新

- (BOOL)executeUpdate:(NSString*)sql, ...

- (BOOL)executeUpdateWithFormat:(NSString*)format, ...

- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments

示例

[db executeUpdate:@"UPDATE t_student SET age = ? WHERE name = ?;", @20, @"Jack"]

五、執行查詢

查詢方法

- (FMResultSet *)executeQuery:(NSString*)sql, ...

- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ...

- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments

示例

// 查詢資料

FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_student"];

// 周遊結果集

while ([rs next]) {

    NSString *name = [rs stringForColumn:@"name"];

    int age = [rs intForColumn:@"age"];

    double score = [rs doubleForColumn:@"score"];

}

二、 FMDB使用步驟

  • 下載下傳FMDB檔案GitHub,并将FMDB檔案夾添加到項目中(也可使用CocoaPods導入)
  • 導入

    libsqlite3.0

    架構,導入頭檔案

    FMDatabase.h

  • 代碼實作,與SQLite使用步驟相似,建立資料庫路徑,獲得資料庫路徑,打開資料庫,然後對資料庫進行增、删、改、查操作,最後關閉資料庫。
iOS FMDB 資料庫~詳解 //聯系人:石虎  QQ: 1224614774昵稱:嗡嘛呢叭咪哄

step.png

資料庫建立

建立FMDatabase對象時參數為SQLite資料庫檔案路徑,該路徑可以是以下三種方式之一

  • 檔案路徑。該檔案路徑無需真實存在,如果不存在會自動建立
  • 空字元串(@“”)。表示會在臨時目錄建立一個空的資料庫,當FMDatabase連接配接關閉時,檔案也會被删除
  • NULL。将建立一個内在資料庫,同樣的,當FMDatabase連接配接關閉時,資料将會被銷毀
  • 本文中使用的測試模型類.h
iOS FMDB 資料庫~詳解 //聯系人:石虎  QQ: 1224614774昵稱:嗡嘛呢叭咪哄

student.png

資料庫使用

FMDB

架構代碼操作
  • 使用

    FMDataBase

    類建立資料庫
    //1.獲得資料庫檔案的路徑
      NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)  lastObject];                  
    
      NSString *fileName = [doc stringByAppendingPathComponent:@“student.sqlite”];
    
       //2.獲得資料庫
       FMDatabase *db = [FMDatabase databaseWithPath:fileName];
    
     //3.使用如下語句,如果打開失敗,可能是權限不足或者資源不足。通常打開完操作操作後,需要調用 close 方法來關閉資料庫。在和資料庫互動 之前,資料庫必須是打開的。如果資源或權限不足無法打開或建立資料庫,都會導緻打開失敗。
     if ([db open])
      {
            //4.創表
          BOOL result = [db executeUpdate:@“CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);”];
           if (result)
            {
              NSLog(@“建立表成功”);
            }
      }
               
  • 檢視sql表
    • 根據路徑fileName在Finder中搜尋.sqlite檔案,并複制到桌面
    • 使用火狐浏覽器工具下的SQLite Manager打開.sqlite檔案
      iOS FMDB 資料庫~詳解 //聯系人:石虎  QQ: 1224614774昵稱:嗡嘛呢叭咪哄
      2.png
    • 資料表結構
iOS FMDB 資料庫~詳解 //聯系人:石虎  QQ: 1224614774昵稱:嗡嘛呢叭咪哄

sql.png

使用

FMDataBase

類執行資料庫指令SQL

一切不是SELECT指令的指令都視為更新。這包括 CREAT,UPDATE,INSERT,ALTER,BEGIN,COMMIT,DETACH,DELETE,DROP,END,EXPLAIN,VACUUM,REPLACE等。

簡單來說,隻要不是以SELECT開頭的指令都是更新指令。

執行更新傳回一個BOOL值。YES表示 執行成功,否則表示有錯誤。你可以調用 -lastErrorMessage 和 -lastErrorCode方法來得到更多資訊。

  • 使用

    FMDataBase

    類執行資料庫插入指令SQL

    insert into

    int age = 42;
    
     //1.executeUpdate:不确定的參數用?來占位(後面參數必須是oc對象,;代表語句結束)
     [self.db executeUpdate:@“INSERT INTO t_student (name, age) VALUES (?,?);”,name,@(age)];
    
        //2.executeUpdateWithForamat:不确定的參數用%@,%d等來占位 (參數為原始資料類型,執行語句不區分大小寫)
     [self.db executeUpdateWithForamat:@“insert into t_student (name,age) values (%@,%i);”,name,age];
    
        //3.參數是數組的使用方式
     [self.db executeUpdate:@“INSERT INTO     
     t_student(name,age) VALUES  (?,?);”withArgumentsInArray:@[name,@(age                 )]];                
  • 使用

    FMDataBase

    類執行資料庫删除指令SQL

    delete

    //1.不确定的參數用?來占位 (後面參數必須是oc對象,需要将int包裝成OC對象)
      int idNum = ;
        [self.db executeUpdate:@“delete from t_student where id = ?;”,@(idNum)];
    
       //2.不确定的參數用%@,%d等來占位
        [self.db executeUpdateWithFormat:@“delete from t_student where name = %@;”,@“apple_name”];
               
  • 使用

    FMDataBase

    類執行資料庫修改指令SQL

    update

    //修改學生的名字
      [self.db executeUpdate:@“update t_student set name = ? where name = ?”,newName,oldName];                
  • 使用

    FMDataBase

    類執行資料庫查詢指令SQL

    select ... from

    • SELECT指令就是查詢,執行查詢的方法是以-excuteQuery開頭的。
    • 執行查詢時,如果成功傳回FMResultSet對象,錯誤傳回nil。與執行更新相當,支援使用NSError參數。
    • 同時,你也可以使用-lastErrorCode和-lastErrorMessage獲知錯誤資訊。
  • FMResultSet

    擷取不同資料格式的方法
    • intForColumn:
    • longForColumn:
    • longLongIntForColumn: 
    • boolForColumn:
    • doubleForColumn:
    • stringForColumn:
    • dataForColumn:
    • dataNoCopyForColumn:
    • UTF8StringForColumnIndex: 
    • objectForColumn:
  • 使用

    FMResultSet

    擷取查詢語句結果
    //查詢整個表
    FMResultSet *resultSet = [self.db execute Query:@“select * from t_student;”];
    
     //根據條件查詢
    FMResultSet *resultSet = [self.db executeQuery:@“select * from t_student where id<?;”@()];
    
     //周遊結果集合   
    
    while ([resultSet  next])
    
       {
        int idNum = [resultSet intForColumn:@“id”];
    
        NSString *name = [resultSet    
        objectForColumn:@“name”];
    
        int age = [resultSet intForColumn:@“age”];
      }
               
  • 使用

    FMDataBase

    類執行資料庫銷毀指令SQL

    drop ...

    //如果表格存在 則銷毀
      [self.db executeUpadate:@“drop table if exists t_student;”];                
  • 使用

    FMDatabaseQueue

    類實作多線程操作
    在多個線程中同時使用一個FMDatabase執行個體是不明智的。現在你可以為每 個線程建立一個FMDatabase對象,不要讓多個線程分享同一個執行個體,他無 法在多個線程中同僚使用。否則程式會時不時崩潰或者報告異常。是以,不要 初始化FMDatabase對象,然後在多個線程中使用。這時候,我們就需要使 用FMDatabaseQueue來建立隊列執行事務。
    //1.建立隊列
     FMDatabaseQueue *queue = [FMDatabaseQueue   
     databaseQueueWithPath:aPath];
      __block BOOL whoopsSomethingWrongHappened = true;
    
     //2.把任務包裝到事務裡
     [queue inTransaction:^(FMDatabase *db, BOOL *rollback) 
       {  
     whoopsSomethingWrongHappened &=  [db     executeUpdate:@“INSERT INTO myTable VALUES (?)”,     [NSNumber numberWith:]];
    whoopsSomethingWrongHappened &= [db
    executeUpdata:@“INSERT INTO myTable VALUES (?)”, 
    [NSNumber numberWithInt:]];
    
    whoopsSomethingWrongHappened &= [db  
    executeUpdata:@“INSERT INTO myTable VALUES (?)”[NSNumber  
    numberWithInt:]];
    //如果有錯誤 傳回
    if (!whoopsSomethingWrongHappened)
      { 
        *rollback = YES;
          return;
      }
    }];
               

    好了,到此為止,相信你已經能夠使用FMDB進行資料持久化了,它的好與壞 隻有在不斷地使用過程中才能發現了解。是以,希望大家學會了以後還是要多 寫多練多使用。另外,誠心希望大家多提寶貴意見,或者溝通一些好的想法。

    謝謝!!!