我是iPhone开发和Mac OS的新手,请忍受愚蠢的查询。但我努力深入,但无法找到问题的解决方案。
我已经通过命令提示符在sqlite中创建了一个数据库。数据库保存在Users / DNamto / resources.db
中但是当我尝试使用以下代码片段在我的iPhone应用程序中打开此数据库时
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:@"resources.db"]];
数据库无法打开。 应用程序搜索的数据库路径是: / Users / DNamto / Library / Application Support / iPhone Simulator / 6.0 / Applications / C82C3DAF-4E95-49A7-9A4F-4D69B056DC9D / Documents / resources.db
任何人都可以帮助我获得正确的数据库路径。 我们可以硬编码数据库路径,以便我的应用程序链接到它。如果是,那么请提供代码段。
答案 0 :(得分:1)
你做不到。在实际设备中,您无法获得硬编码路径。
您需要一条相对路径。
此处您的问题是您的数据库不在文档目录中。
您需要将数据库添加到主数据包中,并且在运行时需要检查数据库是否存在于文档目录中,如果不是,则需要使用NSFileManager.
您可以使用以下代码将数据库文件从bundle复制到文档目录。
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"resource.db"];
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"resource.db"];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:folderPath error:&error];
答案 1 :(得分:1)
在应用程序中添加数据库&检查数据库是否存在于doc目录中,如果没有,则需要将其复制到doc目录中然后访问它。 对于cppy,doc目录中的db使用以下代码片段
- (void)copyDatabaseIfNeeded {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:[self getDBPath]];
NSString *databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"dbname.sqlite"];
if(success)
{
return;// remove old one.
}
[fileManager copyItemAtPath:databasePath toPath:[self getDBPath] error:nil];
}
使用以下代码段打开数据库
-(void)openDatabase
{
@try
{
[self copyDatabaseIfNeeded];
if(sqlite3_open([[self getDBPath] UTF8String], &mainDatabase)==SQLITE_OK)
{
NSLog(@"Database opened");
}
}
@catch (NSException *exception)
{
NSLog(@"Exception in openDatabase %@ :%@",exception.name,exception.reason);
}
}
- (NSString *)getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"dbname.sqlite"];
}
使用以下代码段关闭数据库。
-(void)closeDatabase:(sqlite3_stmt*)statement
{
@try
{
sqlite3_finalize(statement);
sqlite3_close(mainDatabase);
}
@catch (NSException *exception)
{
NSLog(@"Exception in DatabaseController closeDatabase %@ :%@",exception.name,exception.reason);
}
}