【问题标题】:How to add a .sql file to sqlite db in Xcode [duplicate]如何在Xcode中将.sql文件添加到sqlite db [重复]
【发布时间】:2013-07-15 11:52:10
【问题描述】:

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

【问题讨论】:

    标签: ios xcode sqlite xcode4.2


    【解决方案1】:

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

    【讨论】:

    • 我们用来从.db 文件中读取数据库对吧?相反,我有一个.sql 文件,而不是.sqlite
    • 没问题,您只需将文件拖放到您的文件夹中即可开始工作。文件扩展名的类型无关紧要。如果您有副本,然后拖放到您的工作文件夹中称为沙盒。
    • 我的疑问是,.sql 文件实际上具有创建数据库和表以及将值插入表中的命令。如何使用 sql 命令访问此类文件中的值?
    • 如何获取 [self getDBPath] ?
    • '[self getDBPath]' 显示错误。如何克服?
    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    相关资源
    最近更新 更多