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