当我使用sqlcipher加密我的数据库,并在FMDatabaseQueue中调用inDatabase
——成功!
但是当我将 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/
最佳答案
调用 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];
}];
关于iOS sqlcipher fmdb inTransaction “File is encrypted or is not a database”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33473991/