2015-11-02 94 views
3

當我使用sqlcipher加密我的數據庫並在FMDatabaseQueue中調用inDatabase - 成功!iOS sqlcipher fmdb inTransaction「文件已加密或不是數據庫」

但是當我將inDatabase更改爲inTransaction時,控制檯顯示「文件已加密或不是數據庫」。

代碼:

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:st_dbPath]; 

// success 
[queue inDatabase:^(FMDatabase *db) { 

    [db setKey:st_dbKey]; 
    [db executeUpdate:@"INSERT INTO t_user VALUES (16)"]; 
}]; 

// fail : File is encrypted or is not a database 
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) { 

    [db setKey:st_dbKey]; 
    [db executeUpdate:@"INSERT INTO t_user VALUES (17)"]; 
}]; 

而且加密數據庫代碼:

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentDir = [documentPaths objectAtIndex:0]; 
NSString *ecDB = [documentDir stringByAppendingPathComponent:st_dbEncryptedName]; 

// SQL Query. NOTE THAT DATABASE IS THE FULL PATH NOT ONLY THE NAME 
const char* sqlQ = [[NSString stringWithFormat:@"ATTACH DATABASE '%@' AS encrypted KEY '%@';", ecDB, st_dbKey] UTF8String]; 

sqlite3 *unencrypted_DB; 
if (sqlite3_open([st_dbPath UTF8String], &unencrypted_DB) == SQLITE_OK) { 

    // Attach empty encrypted database to unencrypted database 
    sqlite3_exec(unencrypted_DB, sqlQ, NULL, NULL, NULL); 

    // export database 
    sqlite3_exec(unencrypted_DB, "SELECT sqlcipher_export('encrypted');", NULL, NULL, NULL); 

    // Detach encrypted database 
    sqlite3_exec(unencrypted_DB, "DETACH DATABASE encrypted;", NULL, NULL, NULL); 

    sqlite3_close(unencrypted_DB); 
} 
else { 
    sqlite3_close(unencrypted_DB); 
    NSAssert1(NO, @"Failed to open database with message '%s'.", sqlite3_errmsg(unencrypted_DB)); 
} 

從那裏來的加密代碼:http://www.guilmo.com/fmdb-with-sqlcipher-tutorial/

回答

2

調用inTransaction導致SQL語句begin exclusive transaction要在執行您的數據庫在調用您的完成塊之前。因此,在您有機會致電setKey之前執行SQL。

你也可以使用inDatabase和傳遞迴這樣的FBDatabase實例調用beginTransaction

[self.queue inDatabase:^(FMDatabase *db) { 

    [db setKey:st_dbKey]; 
    [db beginTransaction]; 

    [db executeUpdate:@"INSERT INTO t_user VALUES (17)"]; 

    [db commit]; 
}]; 
+0

它的工作,很想你。 – saitjr

相關問題