SQLite第三方框架FMDB的使用,以及使用FMDatabaseQueue保證線程安全

(1)下載地址:https://github.com/ccgus/fmdbgit

 

(2)注意點github

——語句能夠帶分號「;」,也能夠省略分號。sql

——一樣須要添加「libsqlite3.dylib」庫才能使用。數據庫

——移動端的開發中,通常不關閉數據庫,即不怎麼使用[self.db close];,由於每次從新打開比較耗性能,且每次程序關閉時數據庫天然會同時關閉。安全

 

(3)用法dom

 

#import "ViewController.h"
#import "FMDB.h"

@interface ViewController ()
@property(nonatomic,strong) FMDatabase *db;
- (IBAction)insert:(id)sender;
- (IBAction)delete:(id)sender;
- (IBAction)update:(id)sender;
- (IBAction)select:(id)sender;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *filePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"fmdb.sqlite"];
    //建立數據庫
    self.db=[FMDatabase databaseWithPath:filePath];
    //打開數據庫
    if ([self.db open]) {
        NSLog(@"打開數據庫成功");
        //建立表格,除了select外,全部的操做都是更新
        BOOL createTableResult=[self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT,name text,age integer)"];
        if (createTableResult) {
            NSLog(@"建立表成功");
        }else{
            NSLog(@"建立表失敗");
        }
    }else{
        NSLog(@"打開數據庫失敗");
    }
}

- (IBAction)insert:(id)sender {
    for (int index=0; index<50; index++) {
        NSString *s_name=[NSString stringWithFormat:@"Andy%d",arc4random()%100];
        NSNumber *s_age=@(arc4random()%100);
        [self.db executeUpdate:@"INSERT INTO t_student(name,age) VALUES(?,?)",s_name,s_age];
    }
}

- (IBAction)delete:(id)sender {
    [self.db executeUpdate:@"DELETE FROM t_student WHERE id=?",@1];
}

- (IBAction)update:(id)sender {
    [self.db executeUpdate:@"UPDATE t_student SET name='Jack' WHERE id=?",@2];
}

- (IBAction)select:(id)sender {
    //獲取結果集,返回參數就是查詢結果
    FMResultSet *rs=[self.db executeQuery:@"SELECT * FROM t_student WHERE age>?",@50];
    while ([rs next]) {
        int ID=[rs intForColumn:@"id"];
        NSString *NAME=[rs stringForColumn:@"name"];
        int AGE=[rs intForColumn:@"age"];
        NSLog(@"%d %@ %d",ID,NAME,AGE);
    }
}
@end


(4)使用FMDatabaseQueue保證線程安全(建議之後都這麼作)性能

 

——主要就是在建立數據庫的時候,默認已經打開數據庫atom

——隨後的不少操做,由於須要在數據庫中操做,因此須要利用隊列的inDataBase方法調出數據庫,在block中執行操做代碼。線程

 

#import "ViewController.h"
#import "FMDB.h"

@interface ViewController ()
@property(nonatomic,strong) FMDatabaseQueue *queue;
- (IBAction)insert:(id)sender;
- (IBAction)delete:(id)sender;
- (IBAction)update:(id)sender;
- (IBAction)select:(id)sender;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *filePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"fmdb.sqlite"];
    //建立數據庫,並加入到隊列中,此時已經默認打開了數據庫,無須手動打開,只須要從隊列中去除數據庫便可
    self.queue=[FMDatabaseQueue databaseQueueWithPath:filePath];
    //取出數據庫,這裏的db就是數據庫,在數據庫中建立表
    [self.queue inDatabase:^(FMDatabase *db) {
        //建立表
        BOOL createTableResult=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT,name text,age integer)"];
        if (createTableResult) {
            NSLog(@"建立表成功");
        }else{
            NSLog(@"建立表失敗");
        }
    }];
}

- (IBAction)insert:(id)sender {
    [self.queue inDatabase:^(FMDatabase *db) {
        for (int index=0; index<50; index++) {
            NSString *s_name=[NSString stringWithFormat:@"Andy%d",arc4random()%100];
            NSNumber *s_age=@(arc4random()%100);
            [db executeUpdate:@"INSERT INTO t_student(name,age) VALUES(?,?)",s_name,s_age];
        }
    }];
}

- (IBAction)delete:(id)sender {
    [self.queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"DELETE FROM t_student WHERE id=?",@1];
    }];
}

- (IBAction)update:(id)sender {
    [self.queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"UPDATE t_student SET name='Jack' WHERE id=?",@2];
    }];
}

- (IBAction)select:(id)sender {
    [self.queue inDatabase:^(FMDatabase *db) {
        //獲取結果集,返回參數就是查詢結果
        FMResultSet *rs=[db executeQuery:@"SELECT * FROM t_student WHERE age>?",@50];
        while ([rs next]) {
            int ID=[rs intForColumn:@"id"];
            NSString *NAME=[rs stringForColumn:@"name"];
            int AGE=[rs intForColumn:@"age"];
            NSLog(@"%d %@ %d",ID,NAME,AGE);
        }
    }];
}


(5)若是要保證多個操做同時成功或者同時失敗,用事務,即把多個操做放在同一個事務中。orm

 

——FMDB中,拿到數據庫直接操做事務,以下:

 

- (IBAction)update:(id)sender {
    [self.queue inDatabase:^(FMDatabase *db) {
        [db beginTransaction];
        [db executeUpdate:@"UPDATE t_student SET name='Jack' WHERE id=?",@2];
        [db executeUpdate:@"UPDATE t_student SET name='Tomy' WHERE id=?",@3];
        //發現狀況不對時,主動回滾用下面語句。不然是根據commit結果,如成功就成功,如不成功纔回滾
        [db rollback];
        [db executeUpdate:@"UPDATE t_student SET name='Eric' WHERE id=?",@4];
        [db commit];
    }];
}


上面由於用的是FMDB封裝好的,其實原生的代碼是這樣的:

 

 

[db executeUpdate:@"BEGIN TRANSACTION"];
[db executeUpdate:@"ROLLBACK TRANSACTION"];
[db executeUpdate:@"COMMIT TRANSACTION"];

 

 

——FMDB中,也能夠直接利用隊列進行事務操做,隊列中的打開、關閉、回滾事務等都已經被封裝好了。

 

- (IBAction)update:(id)sender {
    [self.queue inDatabase:^(FMDatabase *db) {
        [self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
            [db executeUpdate:@"UPDATE t_student SET name='Jack' WHERE id=?",@2];
            [db executeUpdate:@"UPDATE t_student SET name='Tomy' WHERE id=?",@3];
            //發現狀況不對時,主動回滾用下面語句。
            *rollback=YES;
            [db executeUpdate:@"UPDATE t_student SET name='Eric' WHERE id=?",@4];
        }];
}
相關文章
相關標籤/搜索