gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 05:40:31 25 4
gpt4 key购买 nike

当我使用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 在调用完成 block 之前在您的数据库上执行。因此,该 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];
}];

关于iOS sqlcipher fmdb inTransaction “File is encrypted or is not a database”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33473991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com