如何在Xcode中将.sql文件添加到sqlite db

Har*_*nan 4 sqlite xcode ios xcode4.2

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

小智 5

如果您已创建.sqlite文件并在其中包含表,则将.sqlite文件添加到xcode中,就像从桌面拖动到您的包中一样(参考资料).然后使用NSFileManager访问sqlite文件.您需要编写方法对于createdatabase和initialize database,您还可以在文档文件夹/模拟器文件夹中看到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");
}
Run Code Online (Sandbox Code Playgroud)

  • 如何获得[self getDBPath]? (2认同)