IOS 數據存儲之 FMDB 詳解


  FMDB是用於進行數據存儲的第三方的框架,它與SQLite與Core Data相比較,存在很多優勢。

  FMDB是面向對象的,它以OC的方式封裝了SQLite的C語言API,使用起來更加的方便,不需要過多的關心數據庫操作的知識。但是它本身也存在一些問題,比如跨平台,因為它是用oc的語言封裝的,所以只能在ios開發的時候使用,如果想實現跨平台的操作,來降低開發的成本和維護的成本,就需要使用比較原始的SQLite。

  Core Data是ORM的一種體現,使用Core Data需要用到模型數據的轉化,雖然操作簡單,不需要直接操作數據庫,但是性能沒有直接使用SQLite高。但是SQLite使用的時候需要使用c語言中的函數,操作比較麻煩,因此需要對它進行封裝。但是如果只是簡單地封裝,很可能會忽略很多重要的細節,比如如何處理並發以及安全性更問題。

  因此,在這里推薦使用第三方框架FMDB,它是對libsqlite3框架的封裝,用起來的步驟與SQLite使用類似,並且它對於多線程的同時操作一個表格時進行了處理,也就意味着它是線程安全的。FMDB是輕量級的框架,使用靈活,它是很多企業開發的首選。

 FMDB中重要的類

FMDatabase:一個FMDatabase對象就代表一個單獨的SQLite數據庫,用來執行SQL語句 

FMResultSet:使用FMDatabase執行查詢后的結果集

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

 FMDB使用步驟

  1. 下載FMDB文件 fmdb下載地址  ,將FMDB文件夾添加到項目中

  2. 導入sqlite框架,導入FMDatabase.h文件

 

  3.與SQLite使用步驟類似,需要獲取數據庫文件路徑,然后獲得數據庫,並打開數據庫,然后數據庫進行操作,最后關閉數據庫。代碼如下所示:

//  ViewController.m
//  JRFMDB
//
//  Created by jerehedu on 15/6/18.
//  Copyright (c) 2015年 jerehedu. All rights reserved.
//

#import "ViewController.h"
#import "FMDatabase.h"

@interface ViewController ()
@property (nonatomic, strong) FMDatabase *db;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //導入sqlite框架,導入FMDB文件夾
    
    //1.獲得數據庫文件的路徑
    NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName=[doc stringByAppendingPathComponent:@"student.sqlite"];
    NSLog(@"fileName = %@",fileName);
    
    //2.獲得數據庫
    FMDatabase *db = [FMDatabase databaseWithPath:fileName];
    
    //3.打開數據庫
    if ([db open]) {
        NSLog(@"ok");
        
        //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(@"創表成功");
        }else{
            NSLog(@"創表失敗");
        }
    }
    self.db=db;
    
    //插入數據
    [self insertStu];
    [self deleteStu:6];
    [self updateStu:@"apple7_name" :@"7777"];
    
    [self queryStu];
    [self dropStu];
    [self insertStu];
    [self queryStu];
    
    //6.關閉數據庫
    [self.db close];
}

#pragma mark 插入數據
-(void)insertStu
{
    for (int i=0; i<10; i++)
    {
        NSString *name = [NSString stringWithFormat:@"1apple%i_name",i];
        int age = arc4random()%3+20;
        
        //1.  executeUpdate : 不確定的參數用?來占位 (后面參數必須都是oc對象)
        [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?,?);",name,@(age)];
        
        //2.  executeUpdateWithFormat : 不確定的參數用%@、%d等來占位 (參數為原始數據類型)
        //        [self.db executeUpdateWithFormat:@"insert into t_student (name, age) values (%@, %i);",name,age];
        
        //3. 數組
        //        [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?,?);" withArgumentsInArray:@[name,@(age)]];
    }
    
}

#pragma mark 刪除數據
-(void)deleteStu:(int)idNum
{
    //a.  executeUpdate : 不確定的參數用?來占位 (后面參數必須都是oc對象)
    //    [self.db executeUpdate:@"delete from t_student where id=?;",@(idNum)];
    
    //b.  executeUpdateWithFormat : 不確定的參數用%@、%d等來占位
    //    [self.db executeUpdateWithFormat:@"delete from t_student where name=%@;",@"apple9_name"];
}

#pragma mark 銷毀表格
-(void)dropStu
{
    [self.db executeUpdate:@"drop table if exists t_student;"];
    
    //4.創表
    BOOL result=[self.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(@"再次創表成功");
    }else{
        NSLog(@"再次創表失敗");
    }
}

#pragma mark 修改數據
-(void)updateStu:(NSString *)oldName :(NSString*)newName
{
    //    [self.db executeUpdateWithFormat:@"update t_student set name=%@ where name=%@;",newName,oldName];
    [self.db executeUpdate:@"update t_student set name=? where name=?",newName,oldName];
}

#pragma mark 查詢數據
-(void)queryStu
{
    //1.執行查詢語句
    //    FMResultSet *resultSet = [self.db executeQuery:@"select * from t_student;"];
    FMResultSet *resultSet = [self.db executeQuery:@"select * from t_student where id<?;",@(14)];
    
    //2.遍歷結果集合
    while ([resultSet next]) {
        int idNum = [resultSet intForColumn:@"id"];
        NSString *name = [resultSet objectForColumnName:@"name"];
        int age = [resultSet intForColumn:@"age"];
        NSLog(@"id=%i ,name=%@, age=%i",idNum,name,age);
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

 

  疑問咨詢或技術交流,請加入官方QQ群:JRedu技術交流 (452379712)

 

作者: 傑瑞教育
出處: http://www.cnblogs.com/jerehedu/ 
本文版權歸煙台傑瑞教育科技有限公司和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM