iOS學習——數據庫操作(使用FMDB)

        iOS中原生的SQLite API在使用上相當不友好,在使用時,非常不便。於是,就出現了一系列將SQLite API進行封裝的庫,例如FMDB、PlausibleDatabase、sqlitepersistentobjects等,FMDB (https://github.com/ccgus/fmdb) 是一款簡潔、易用的封裝庫,這一篇文章簡單介紹下FMDB的使用。

在FMDB下載文件後,工程中必須導入如下文件,並使用 libsqlite3.dylib 依賴包。



FMDB同時兼容ARC和非ARC工程,會自動根據工程配置來調整相關的內存管理代碼。

FMDB常用類:

FMDatabase : 一個單一的SQLite數據庫,用於執行SQL語句。
FMResultSet :執行查詢一個FMDatabase結果集,這個和android的Cursor類似。
FMDatabaseQueue :在多個線程來執行查詢和更新時會使用這個類。


創建數據庫:


  1. db = [FMDatabase databaseWithPath:database_path];  

         1、當數據庫文件不存在時,fmdb會自己創建一個。

         2、 如果你傳入的參數是空串:@"" ,則fmdb會在臨時文件目錄下創建這個數據庫,數據庫斷開連接時,數據庫文件被刪除。

         3、如果你傳入的參數是 NULL,則它會建立一個在內存中的數據庫,數據庫斷開連接時,數據庫文件被刪除。


打開數據庫:

  1. [db open]  

返回BOOL型。

關閉數據庫:

  1. [db close]  


數據庫增刪改等操作:

除了查詢操作,FMDB數據庫操作都執行executeUpdate方法,這個方法返回BOOL型。


看一下例子:

創建表:

  1. if ([db open]) {  
  2.         NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS];  
  3.         BOOL res = [db executeUpdate:sqlCreateTable];  
  4.         if (!res) {  
  5.             NSLog(@"error when creating db table");  
  6.         } else {  
  7.             NSLog(@"success to creating db table");  
  8.         }  
  9.         [db close];  
  10.   
  11.     }  


添加數據:

  1. if ([db open]) {  
  2.        NSString *insertSql1= [NSString stringWithFormat:  
  3.                               @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",  
  4.                               TABLENAME, NAME, AGE, ADDRESS, @"張三", @"13", @"濟南"];  
  5.        BOOL res = [db executeUpdate:insertSql1];  
  6.        NSString *insertSql2 = [NSString stringWithFormat:  
  7.                                @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",  
  8.                                TABLENAME, NAME, AGE, ADDRESS, @"李四", @"12", @"濟南"];  
  9.        BOOL res2 = [db executeUpdate:insertSql2];  
  10.          
  11.        if (!res) {  
  12.            NSLog(@"error when insert db table");  
  13.        } else {  
  14.            NSLog(@"success to insert db table");  
  15.        }  
  16.        [db close];  
  17.   
  18.    }  


修改數據:

  1. if ([db open]) {  
  2.         NSString *updateSql = [NSString stringWithFormat:  
  3.                                @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'",  
  4.                                TABLENAME,   AGE,  @"15" ,AGE,  @"13"];  
  5.         BOOL res = [db executeUpdate:updateSql];  
  6.         if (!res) {  
  7.             NSLog(@"error when update db table");  
  8.         } else {  
  9.             NSLog(@"success to update db table");  
  10.         }  
  11.         [db close];  
  12.   
  13.     }  


刪除數據:

  1. if ([db open]) {  
  2.           
  3.         NSString *deleteSql = [NSString stringWithFormat:  
  4.                                @"delete from %@ where %@ = '%@'",  
  5.                                TABLENAME, NAME, @"張三"];  
  6.         BOOL res = [db executeUpdate:deleteSql];  
  7.           
  8.         if (!res) {  
  9.             NSLog(@"error when delete db table");  
  10.         } else {  
  11.             NSLog(@"success to delete db table");  
  12.         }  
  13.         [db close];  
  14.   
  15.     }  


數據庫查詢操作:

查詢操作使用了executeQuery,並涉及到FMResultSet。

  1. if ([db open]) {  
  2.         NSString * sql = [NSString stringWithFormat:  
  3.                           @"SELECT * FROM %@",TABLENAME];  
  4.         FMResultSet * rs = [db executeQuery:sql];  
  5.         while ([rs next]) {  
  6.             int Id = [rs intForColumn:ID];  
  7.             NSString * name = [rs stringForColumn:NAME];  
  8.             NSString * age = [rs stringForColumn:AGE];  
  9.             NSString * address = [rs stringForColumn:ADDRESS];  
  10.             NSLog(@"id = %d, name = %@, age = %@  address = %@", Id, name, age, address);  
  11.         }  
  12.         [db close];  
  13.     }  


FMDB的FMResultSet提供了多個方法來獲取不同類型的數據:


數據庫多線程操作:

        如果應用中使用了多線程操作數據庫,那麼就需要使用FMDatabaseQueue來保證線程安全了。 應用中不可在多個線程中共同使用一個FMDatabase對象操作數據庫,這樣會引起數據庫數據混亂。 爲了多線程操作數據庫安全,FMDB使用了FMDatabaseQueue,使用FMDatabaseQueue很簡單,首先用一個數據庫文件地址來初使化FMDatabaseQueue,然後就可以將一個閉包(block)傳入inDatabase方法中。 在閉包中操作數據庫,而不直接參與FMDatabase的管理。

  1. FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:database_path];  
  2.    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);  
  3.    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);  
  4.      
  5.    dispatch_async(q1, ^{  
  6.        for (int i = 0; i < 50; ++i) {  
  7.            [queue inDatabase:^(FMDatabase *db2) {  
  8.                  
  9.                NSString *insertSql1= [NSString stringWithFormat:  
  10.                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",  
  11.                                       TABLENAME, NAME, AGE, ADDRESS];  
  12.                  
  13.                NSString * name = [NSString stringWithFormat:@"jack %d", i];  
  14.                NSString * age = [NSString stringWithFormat:@"%d", 10+i];  
  15.                  
  16.                  
  17.                BOOL res = [db2 executeUpdate:insertSql1, name, age,@"濟南"];  
  18.                if (!res) {  
  19.                    NSLog(@"error to inster data: %@", name);  
  20.                } else {  
  21.                    NSLog(@"succ to inster data: %@", name);  
  22.                }  
  23.            }];  
  24.        }  
  25.    });  
  26.      
  27.    dispatch_async(q2, ^{  
  28.        for (int i = 0; i < 50; ++i) {  
  29.            [queue inDatabase:^(FMDatabase *db2) {  
  30.                NSString *insertSql2= [NSString stringWithFormat:  
  31.                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",  
  32.                                       TABLENAME, NAME, AGE, ADDRESS];  
  33.                  
  34.                NSString * name = [NSString stringWithFormat:@"lilei %d", i];  
  35.                NSString * age = [NSString stringWithFormat:@"%d", 10+i];  
  36.                  
  37.                BOOL res = [db2 executeUpdate:insertSql2, name, age,@"北京"];  
  38.                if (!res) {  
  39.                    NSLog(@"error to inster data: %@", name);  
  40.                } else {  
  41.                    NSLog(@"succ to inster data: %@", name);  
  42.                }  
  43.            }];  
  44.        }  
  45.    });  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章