問題一: "is currently in use" 出現(xiàn)的場(chǎng)景是這樣的,多線程操作數(shù)據(jù)庫,每個(gè)線程都使用了FMDatabase實(shí)例(注意沒有使用FMDatabaseQueue)。
問題二:“database is locked"出現(xiàn)的場(chǎng)景是這樣的,多線程操作數(shù)據(jù)庫,每個(gè)線程各自創(chuàng)建了FMDatabaseQueue實(shí)例操作數(shù)據(jù)庫,或者一個(gè)線程創(chuàng)建FMDatabaseQueue實(shí)例來操作,而另外的線程創(chuàng)建了FMDatabase實(shí)例來操作。
解決:FMDB多線程操作數(shù)據(jù)庫,必須使用FMDatabaseQueue,必須只創(chuàng)建一個(gè)實(shí)例,也就是多個(gè)線程操作數(shù)據(jù)庫的是同一個(gè)FMDatabaseQueue實(shí)例。
原因:因?yàn)槭紫菷MDatabase是不具備線程安全的,如果兩個(gè)線程中同時(shí)操作數(shù)據(jù)庫,就會(huì)"is currently in use" ;FMDatabasequeue其實(shí)是一個(gè)調(diào)度隊(duì)列(G-C-D),數(shù)據(jù)庫的操作必須是順序執(zhí)行,不能兩個(gè)數(shù)據(jù)庫的操作同時(shí)執(zhí)行,如果是兩個(gè)線程各自創(chuàng)建了FMDatabaseQueue的實(shí)例,線程同時(shí)執(zhí)行時(shí),就會(huì)出現(xiàn)相同的數(shù)據(jù)庫操作同時(shí)觸發(fā),導(dǎo)致”database is locked“,所以必須是一個(gè)FMDatabaseQueue實(shí)例下,多個(gè)線程下同時(shí)操作,其實(shí)是在排在同一個(gè)隊(duì)列中逐一操作的,沒有同時(shí)操作。
PS:以下就是我的解決方式
1 #PRagma mark - 配置數(shù)據(jù)庫單聊 2 +(FMDatabaseQueue *)getSharedDatabaseQueue 3 { 4 static FMDatabaseQueue *my_FMDatabaseQueue=nil; 5 6 if (!my_FMDatabaseQueue) { 7 NSString *path = [kDocuments stringByAppendingPathComponent:@"db_CMBCC.sqlite"]; 8 my_FMDatabaseQueue = [FMDatabaseQueue databaseQueueWithPath:path]; 9 }10 return my_FMDatabaseQueue;11 }
- (void)SaveSingleChatMessage:(MessageEntityModel *)messageEntity{ FMDatabaseQueue *queue = [StoreManagerHelper getSharedDatabaseQueue]; [queue inDatabase:^(FMDatabase *db) { //打開數(shù)據(jù)庫 if ([db open]) { //數(shù)據(jù)庫建表,插入語句 } else { NSLog(@"打開數(shù)據(jù)庫失敗!"); } }];}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注