ios - 如何在 Xcode 中将 .sql 文件添加到 sqlite 数据库

标签 ios xcode sqlite xcode4.2

<分区>

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

最佳答案

如果您已经创建了 .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");
}

关于ios - 如何在 Xcode 中将 .sql 文件添加到 sqlite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17691122/

相关文章:

iphone - UIImagePickerController 媒体类型 kUTTypeMovie 运行时异常

xcode 未找到匹配的配置文件

iPhone sqlite desc 与 asc?

java - 在主机 Java 中连接 SQLite 时遇到问题

android - 如何在不更改主键的情况下执行 SQL Insert 或 Replace like operator?

ios - 如何更改 UIButton 的宽度约束变化方向?

ios - 为什么 WKInterfaceTable 的方法 rowControllerAtIndex 返回 nil?

objective-c - 重写setter方法并获取“xxx的本地声明隐藏实例变量”

ios - 从 API 调用返回的 base64encoded 字符串在数据之后显示为 nil(base64encoded : data) is ran

iOS 7 TableviewCell 彩色线条