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

前端之家收集整理的这篇文章主要介绍了ios – 如何在Xcode中将.sql文件添加到sqlite db前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > How should I specify the path for an sqlite db in an iPhone project?                                    3个
我正在编写一个离线iPhone应用程序,我需要从一个包含少量表的数据库中读取和显示.这些表中有超过100,000个条目,因此几乎不可能单独输入所有条目.我已经下载了整个数据库的.sql文件.现在我如何将db导入sqlite / Xcode,以便我可以随时开始访问它中的数据?
编辑:我已经看到,使用数据库时,使用的文件扩展名是.db文件.无论如何我可以将.sql文件转换为.db文件.如果我能做到这一点,我可以通过将它放在项目目录中来简单地访问.db文件吗?

解决方法

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

猜你在找的Xcode相关文章