FMDB多線程讀寫問題,使用FMDataBaseQueue操作可以解決同時打開一個鏈接de讀寫問題


現在ios里使用的數據庫一般都是Sqlite,但是使用Sqlite有個不太好的地方就是在多線程的時候,會出現問題,sqlite只能打開一個讀或者寫連結。這樣的話多線程就會碰到資源占用的問題。

 

最開始是使用FMDB,FMDB的早期版本不能解決這個問題,后來FMDB更新了,新版本的FMDB能夠很好的解決這個多線程使用Sqlite 。

FMDB github網址  https://github.com/ccgus/fmdb 最新版的請到github取下載。

 

本文演示了使用FMDB通過多線程來讀和寫數據庫操作。

1.建立數據庫表,我采用的是Firefox的Sqlite manager 來建立的。

  建表sql如下

 CREATE TABLE "tbl_user" ("_id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , "name" VARCHAR(30), "password" VARCHAR(30))

 

 2. 建立數據表的映射實體UserEntity

復制代碼
#import <Foundation/Foundation.h>

@interface UserEntity : NSObject
{
     int _id;
    NSString *name;
    NSString *password;
}

@property (nonatomic, assign) int ID;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *password;
復制代碼

@end 

 

3. 建立操作數據庫的dao

復制代碼
//
//   DbDao.m
//   SqliteTest
//
//   Created by foxwang on 12-4-9.
//   Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import  " DbDao.h "
#import  " DbFileManager.h "

#import  " FMDatabase.h "
#import  " FMDatabaseAdditions.h "
#import  " FMDatabasePool.h "
#import  " FMDatabaseQueue.h "
#import  " UserEntity.h "

static DbDao *gSharedInstance = nil;

@implementation DbDao
@synthesize dbFile;
@synthesize dbQueue;

+(DbDao *)sharedInstance
{
    @synchronized(self)
    {
         if (gSharedInstance == nil)
            gSharedInstance = [[DbDao alloc] init];
    }
     return gSharedInstance;    
}

- ( void)dealloc
{
    [self.dbFile release];
    self.dbQueue = nil;
    [super dealloc];
}

- ( id)init
{
    
    self = [super init];
     if (self)
    {
        self.dbFile = [DbFileManager dbFilePath];
        self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:self.dbFile];
        
        
    }
     return  self;
}


- (UserEntity *)rsToUser:(FMResultSet*)rs
{
    UserEntity *user = [[[UserEntity alloc] init] autorelease];
    user.ID = [rs intForColumn: @" _id "];
    user.name = [rs stringForColumn: @" name "];
    user.password = [rs  stringForColumn: @" password "];
     return user;
}

- ( void)addUser:(UserEntity *)user
{
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [db open];
        NSString *sql =  @" insert into tbl_user(name, password) values (?, ?) ";
        [db executeUpdate:sql,user.name, user.password];
        [db close];
    }];  
}

- (NSArray *)getUsers;
{
    __block NSMutableArray *users = [[[NSMutableArray alloc] init] autorelease];  
    [self.dbQueue inDatabase:^(FMDatabase *db)   {
        [db open];
        NSString *sql =  @" select * from tbl_user  ";
        FMResultSet *rs = [db executeQuery:sql];
         while ([rs next])
        {
            [users addObject:[self rsToUser :rs]]; 
        }
        [db close];
    }];
     return users;
}
復制代碼

@end 

 

4. 編寫測試方法

在didFinishLaunchingWithOptions 方法里啟動3個線程 :2個線程寫,1個線程讀

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

復制代碼
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
     //  Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName: @" ViewController " bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    
    
    [NSThread detachNewThreadSelector:@selector(writeDbOne) toTarget:self withObject:nil];
    
    [NSThread detachNewThreadSelector:@selector(readDb) toTarget:self withObject:nil];
    
    [NSThread detachNewThreadSelector:@selector(writeDbTwo) toTarget:self withObject:nil];
    
     return YES;
}
復制代碼

 

復制代碼
- ( void)writeDbOne
{
    DbDao *dao = [DbDao  sharedInstance];
     for ( int i =  0; i <  500; i++)
    {
        @autoreleasepool 
        {
             UserEntity *user = [[[UserEntity alloc] init] autorelease];
             user.name = [NSString stringWithFormat: @" name %d ", i];
             user.password = [NSString stringWithFormat: @" password %d ", i];
             [dao addUser:user];
             NSLog( @" writeDbOne %d  ", i);
        }
       
    }
}

- ( void)writeDbTwo
{
    DbDao *dao = [DbDao  sharedInstance];
     for ( int i =  600; i <  1200; i++)
    {
        @autoreleasepool 
        {
            UserEntity *user = [[[UserEntity alloc] init] autorelease];
            user.name = [NSString stringWithFormat: @" name %d ", i];
            user.password = [NSString stringWithFormat: @" password %d ", i];
            [dao addUser:user];
            NSLog( @" writeDbTwo %d  ", i);
        }
        
    }
}

- ( void)readDb
{
     DbDao *dao = [DbDao  sharedInstance];
     NSArray *users =   [dao getUsers];
     NSLog( @" %@ ", users);
復制代碼

 

最后查看數據庫信息,數據成功插入

結論 :使用新的FMDB ,很好的解決了多線程問題

項目文件下載


免責聲明!

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



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