FMDatabaseQueue错误:数据库已锁定

时间:2014-08-15 17:33:09

标签: ios objective-c multithreading sqlite fmdb

我有一个在后台线程中运行的方法,因此(据我所知)我需要使用FMDatabaseQueue来安全可靠地访问我的SQLite数据库。

我正在进行查询以检查是否存在记录,之后我会立即UPDATEINSERT,具体取决于结果。

第一个查询运行正常,我得到一个计数,但随后的查询不会运行。这是我得到的错误:

  

调用sqlite3_step的未知错误(5:数据库被锁定)eu

这是我的代码:

//Establish database queue
NSString *path = [[PPHelpers documentsPath] stringByAppendingPathComponent:@"PilotPro2.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];

//Start thread-safe database queue
[queue inDatabase:^(FMDatabase *dbq) {

    NSUInteger count;

    //The other parameters in this query are provided beforehand
    NSString *query = [NSString stringWithFormat:@"SELECT COUNT(%@) AS counter FROM %@ WHERE %@ = '%@'",columnID, model, columnID, dict[columnID]];

    FMResultSet *countResult = [dbq executeQuery:query]; //This works fine
    while([countResult next]) {
        count = [countResult intForColumn:@"counter"];
    }

    [countResult close];

    if(count > 0){      
        //--- UPDATE
        //-- This is where FMDB throws the error...
        [dbq executeUpdate:[PPDatabase editAircraftQuery:dict[columnID]], dict[@"aircraftRegistration"], dict[@"makeModel"], dict[@"categoryClass"], dict[@"highPerformance"], dict[@"complex"], dict[@"turbine"], dict[@"turboprop"], dict[@"tailwheel"], dict[@"active"]];

    }else{      
        //--- INSERT      
        [dbq executeUpdate:[PPDatabase addAircraftQuery], dict[@"aircraftID"], dict[@"aircraftRegistration"], dict[@"makeModel"], dict[@"categoryClass"], dict[@"highPerformance"], dict[@"complex"], dict[@"turbine"], dict[@"turboprop"], dict[@"tailwheel"], dict[@"active"]];
    }
}];

我是否需要以某种方式将SELECT查询与其他查询分开?知道为什么我的数据库在第一次查询后被锁定了吗?

1 个答案:

答案 0 :(得分:3)

我有同样的问题。我使用全局队列

创建了sharedInstance

<强> context.h

@interface context : NSObject
{
    FMDatabaseQueue *_queue;
}

+ (context *)sharedInstance;
@property(strong, nonatomic, readwrite) FMDatabaseQueue *queue;
@end

<强> context.m

#import "context.h"

@implementation context

@synthesize queue = _queue;

+ (context *)sharedInstance {
    static dispatch_once_t onceToken;
    static context *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[context alloc] init];
    });
    return instance; 
}

- (id)init {
    self = [super init];
    if (self) {
        _queue          = [FMDatabaseQueue databaseQueueWithPath:YOUR_SQLITE_FILE_PATH];

    }
    return self; 
}

@end

如何使用

context *appContext = [context sharedInstance];

[appContext.queue inDatabase:^(FMDatabase *db) {
FMResultSet *results = [db executeQuery:@"SELECT * FROM something"];

if([results next]) {
    NSLog(@"results dump = %@", [results resultDictionary]);
}
[results close];