iOS sqlcipher fmdb inTransaction “文件已加密或不是数据库”

iOS sqlcipher fmdb inTransaction “File is encrypted or is not a database”

当我使用sqlcipher加密我的数据库,并在FMDatabaseQueue中调用inDatabase——成功!

但是当我将 inDatabase 更改为 inTransaction 时,控制台显示 "File is encrypted or is not a database"。

代码:

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/

调用 inTransaction 会导致 SQL 语句 begin exclusive transaction 在调用完成块之前在您的数据库上执行。因此 SQL 在您有机会调用 setKey.

之前执行

您可以改为使用 inDatabase 并在传回的 FBDatabase 实例上调用 beginTransaction,如下所示:

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

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

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

    [db commit];
}];

Gus Hovland 的答案有效,但我认为更好的方法是将 inTransaction: 更改为 inDeferredTransaction:。来自 FMDB 的 inTransaction 文档:

" 与 SQLite 的 BEGIN TRANSACTION 不同,此方法当前执行 独家交易,而不是延迟交易。这种行为 在 FMDB 的未来版本中可能会发生变化,因此此方法 最终可能会采用标准的 SQLite 行为并执行 延期交易。如果你真的需要独家交易,那就是 建议您改用 inExclusiveTransaction,不仅 使您的意图明确,同时也让您的代码经得起未来考验。"