ios - Xcode中如何使用已有的数据库文件,读写?

标签 ios xcode sqlite

我对 Xcode 和 sqlite 有点陌生。现在我有一个名为“mydb.db”的数据库文件,它已经有一些表和数据。我把它放在我的 mac 文件夹中,然后将它拖到“支持文件”下的 Xcode 项目中。

这是我的代码,但我发现我只能读取这个“mydb.db”,而不能向其中插入数据!当我通过 sqlite 管理器执行我的代码后打开“mydb.db”时,我不能 找到应该插入的数据!

谁能告诉我如何解决这个问题?非常感谢!

NSString *dbFilePath = [[NSBundle mainBundle] pathForResource:@"mydb" ofType:@"db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbFilePath]

    [queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"INSERT INTO Focus VALUES (?,?,?)" withArgumentsInArray:@[@"100000000",@2,@2]];

    }];

最佳答案

通过将 sqlite db 文件添加到 Xcode 中的 Supporting Files 组,您只是将该文件添加到应用程序的包中,以便在构建过程中将其与所有其他资源打包在一起。因为应用程序无法写入到它的包中,所以您必须将 sqlite 数据库文件从包中复制到可写位置,例如

#define FORCE_RECOPY_DB NO

- (void)copyDatabaseIfNeeded {
    NSFileManager *fm = [[NSFileManager alloc] init];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *destinationPath = [documentsPath stringByAppendingPathComponent:@"pte.sqlite"];

    void (^copyDb)(void) = ^(void){
        NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"pte" ofType:@"sqlite"];
        NSAssert1(sourcePath, @"source db does not exist at path %@",sourcePath);

        NSError *copyError = nil;
        if( ![fm copyItemAtPath:sourcePath toPath:destinationPath error:&copyError] ) {
            DDLogError(@"ERROR | db could not be copied: %@", copyError);
        }
    };
    if( FORCE_RECOPY_DB && [fm fileExistsAtPath:destinationPath] ) {
        [fm removeItemAtPath:destinationPath error:NULL];
        copyDb();
    }
    else if( ![fm fileExistsAtPath:destinationPath] ) {
        DDLogInfo(@"INFO | db file needs copying");
        copyDb();
    }
}

现在,当您希望打开数据库时,请使用文档路径中的位置。

请注意,您将无法检查项目中的 sqlite 数据库文件并期望找到从您的代码中写入的更改。 (因为您的代码现在将使用复制的 sqlite 文件。)

关于ios - Xcode中如何使用已有的数据库文件,读写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214431/

相关文章:

IOS UISegmentedControl 不在 ios 10 中显示

ios - 将 youtube api 帮助程序集成到 iOS 时出现错误 258

ios - Xcode 自动布局约束 - 为什么默认为负填充?

sqlite - 如何访问 SQL 脚本中最后插入的行 ID?

android - 我应该如何编写 SQLite 查询?

Android Room defaultValue ="CURRENT_TIMESTAMP"不起作用

ios - 我应该在 MonoTouch 应用程序中的何处执行维护

iphone - 我在 iOS 6 中获得了 Facebook 的格式错误的访问 token

iphone - 找不到 -lidn 的库

iphone - NSMutableArray-内存管理