OC(十一):FMDB的事务封装

FMDB我们经常使用,是对 sqlite 的一个很好的封装.但是使用还是有点不太方便,索性就写了一个 manager 类管理,进行 crud 操作.我们知道这四个操作中当遇到大量数据时候,插入和更新操作是最耗时的,所以我们就要使用事务进行操作,到达节省时间的目的,根据经验再插入10W 条数据大概是2.6s, 是不是很6.那么我们就来看看吧.
.h

//
//  FMDBManager.h
//  FMDBManager
//
//  Created by HMC on 2016/10/31.
//  Copyright © 2016年 HMC. All rights reserved.
//

#import 

@interface FMDBManager : NSObject

//需要使用事务
-(BOOL)insert;
-(BOOL)update;

//arr 查询条件
-(NSArray *)select:(NSArray *)arr;
//arr 删除的条件
-(void)delete:(NSArray *)arr;
@end

.m 采用单例模式设置

//
//  FMDBManager.m
//  FMDBManager
//
//  Created by HMC on 2016/10/31.
//  Copyright © 2016年 HMC. All rights reserved.
//

#import "FMDBManager.h"
#import "FMDB.h"


@interface FMDBManager()

@property (strong, nonatomic) FMDatabaseQueue * fmdbQueue;


@end

@implementation FMDBManager

-(instancetype)init{
    
    if ( self = [super init]) {
        //单例模式设计
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            NSLog(@"%@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"user.db"]);
            
            _fmdbQueue = [FMDatabaseQueue databaseQueueWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"user.db"]];
            
            [_fmdbQueue inDatabase:^(FMDatabase *db) {
                
                if ([db executeUpdate:@"create table if not exists user (userid integer primary key autoincrement , username text)"]) {
                    
                    NSLog(@"create table success");
                }else{
                    
                    NSLog(@"create table error");
                }
                
            }];
            
        });
    }
    
    return self;
    
}



-(BOOL)insert{
    
    __block BOOL isSuccess = NO;
    NSString * sql = @"insert into user (username) values ('SJW')";
    
    [_fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        
        @try {
             CFTimeInterval start=  CFAbsoluteTimeGetCurrent();
            //for (int i= 0  ; i< 100000; i++) {
                
                 [db executeUpdate:sql];
            //}
           
            NSLog(@"时间:%f",CFAbsoluteTimeGetCurrent()-start);
        } @catch (NSException *exception) {
            
            
            *rollback = YES;
        } @finally {
            
            *rollback = NO;
            isSuccess = YES;
        }
        
    }];
    
    return isSuccess;
    
}

-(BOOL)update{
    
    __block BOOL isSuccess = NO;
    NSString * sql = @"update user set username = 'SJW'";
    
    [_fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        
        @try {
            
            [db executeUpdate:sql];
        } @catch (NSException *exception) {
            
            //失败了 就回滚数据
            *rollback = YES;
        } @finally {
            
            *rollback = NO;
            isSuccess = YES;
        }
        
    }];
    
    return isSuccess;
    
}

-(NSArray *)select:(NSArray *)arr{
    NSMutableArray * arrs = [NSMutableArray array];
            
    NSString * sql = @"select * from user where 1 = 1";
    if (arr) {
        for (NSString * str in arr) {
            
            [sql stringByAppendingString:[NSString stringWithFormat:@"and %@",str]];
        }
    }
    [_fmdbQueue inDatabase:^(FMDatabase *db) {
       FMResultSet *result = [db executeQuery:sql];
        
        while ([result next]) {
            NSString * username= [result stringForColumn:@"username"];
            NSLog(@"%@",username);
            [arrs addObject:username];
        }
    }];
    
    return arrs;
    
}

-(void)delete: (NSArray *) arr{
    
    NSString * sql = @"DELETE from user where 1 = 1 ";
    if (arr) {
        for (NSString * str in arr) {
            
            [sql stringByAppendingString:[NSString stringWithFormat:@"and %@",str]];
        }
    }
    
    [_fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:sql];
        
        while ([result next]) {
            NSString * username= [result stringForColumn:@"username"];
            NSLog(@"%@",username);
            
        }
    }];
    
}

@end

调用

//
//  ViewController.m
//  FMDBManager
//
//  Created by HMC on 2016/10/31.
//  Copyright © 2016年 HMC. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    FMDBManager * ma = [[FMDBManager alloc]init];
    [ma insert];
    [ma select:@[@"username = 'SJW'"]];
   // [ma update];
    [ma delete:@[@"username = 'songjinwei'"]];
}


@end

你可能感兴趣的:(OC(十一):FMDB的事务封装)