如何在 Xcode 中将 .sql 文件添加到 sqlite db [英] How to add a .sql file to sqlite db in Xcode

查看:41
本文介绍了如何在 Xcode 中将 .sql 文件添加到 sqlite db的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a offline iPhone app in which I need to read and display from a database which consists of a few number of tables. The tables have over 100k entries in it, so it is almost impossible to enter it all individually. I have downloaded the .sql file of the entire db. Now how can I import the db as such into sqlite/Xcode so that I can readily start accessing the data in it?? I have seen that when using a database, the file extension that is used is a .db file. Is there anyway I can convert the .sql file to a .db file. And if I can do that, can I simply access the .db file by placing it in the project directory?

推荐答案

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

If you have created the .sqlite file and have the tables in it,Then add the .sqlite file into xcode like just drag from desktop into your bundle(Resources).And then use NSFileManager to access the sqlite file.You need to write methods for createdatabase and initialize database and also you can see the sqlite file in your documents folder/simulator folder.

- (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 中将 .sql 文件添加到 sqlite db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆