4

我正在编写一个离线 iPhone 应用程序,我需要在其中读取和显示由几个表组成的数据库。这些表中有超过 100k 个条目,因此几乎不可能单独输入所有条目。我已经下载.sql了整个数据库的文件。现在如何将数据库导入到 sqlite/Xcode 中,以便我可以轻松地开始访问其中的数据?编辑:我看到使用数据库时,使用的文件扩展名是.db文件。无论如何我可以将.sql文件转换为.db文件。如果我能做到这一点,我可以.db通过将文件放在项目目录中来简单地访问该文件吗?

4

1 回答 1

5

如果您已创建 .sqlite 文件并在其中包含表,然后将 .sqlite 文件添加到 xcode 中,就像从桌面拖到您的包(资源)中一样。然后使用 NSFileManager 访问 sqlite 文件。您需要编写方法对于创建数据库和初始化数据库,您还可以在您的文档文件夹/模拟器文件夹中看到 sqlite 文件。

- (void)createEditableCopyOfDatabaseIfNeeded {
    NSLog(@"Checking for database file");
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *dbPath = [self getDBPath];
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ihaikudb.sql"];
    BOOL success = [fileManager fileExistsAtPath:dbPath]; 

    NSLog(@"If needed, bundled default DB is at: %@",defaultDBPath);

    if(!success) {
        NSLog(@"Database didn't exist... Copying default from resource dir");
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success) 
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    } else {
        NSLog(@"Database must have existed at the following path: %@", dbPath);
    }
    NSLog(@"Done checking for db file");
}
于 2013-07-17T04:32:26.370 回答