如何在 Xcode 中将 .sql 文件添加到 sqlite db
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17691122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a .sql file to sqlite db in Xcode
提问by Harikrishnan
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??
Edit: 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?
我正在编写一个离线 iPhone 应用程序,我需要在其中读取和显示由几个表组成的数据库。这些表中有超过 10 万个条目,因此几乎不可能单独输入所有条目。我已经下载.sql
了整个数据库的文件。现在如何将数据库导入 sqlite/Xcode,以便我可以轻松开始访问其中的数据?编辑:我已经看到在使用数据库时,使用的文件扩展名是一个.db
文件。无论如何我可以将.sql
文件转换为.db
文件。如果我能做到这一点,我是否可以.db
通过将它放在项目目录中来简单地访问该文件?
回答by NHS
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.
如果您已经创建了 .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");
}