在iphone中集成sqlite
问题描述:
我在我的应用程序中创建数据库,创建Db后,我试图将数据库从应用程序包复制到Doc目录。但是我无法复制它,我得到的错误如 操作无法完成。 (可可错误260) 下面显示的是我在用的代码,请大家帮我解决这个问题在iphone中集成sqlite
dbName="userDetails.db";
returnCode=sqlite3_open(dbName,&handler);
if(returnCode!=SQLITE_OK)
NSLog(@"message---%s",sqlite3_errmsg(handler));
else
NSLog(@"sucess---%d",returnCode);
NSFileManager *fmgr=[NSFileManager defaultManager];
NSError *error;
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path=[paths objectAtIndex:0];
NSString *docPath=[path stringByAppendingPathComponent:@"userDetails.db"];
if(![fmgr fileExistsAtPath:docPath]){
NSString *defaultDBPath=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"userDetails.db"];
if(![fmgr copyItemAtPath:defaultDBPath toPath:docPath error:&error])
NSLog(@"failure message----%@",[error localizedDescription]);
}
答
其实我对你的代码有点困惑。您是否试图以编程方式在应用程序包中创建数据库,然后将其复制到文档目录?如果这是你正在做的事情,那么你需要知道你不能创建或修改应用程序包中的任何内容。您必须在Documents目录中创建该数据库。你应该做这样的事情 -
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString * databasePath = [documentsDir stringByAppendingPathComponent:@"XYZ.sqlite"];
// generate databasePath programmatically
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
// your code here
}
但如果你已经在你的应用程序有一个数据库(而不是动态创建),你只想把它复制到文档目录,那么你应该遵循@Santosh Gurram答案。
答
两件事情浮现在脑海中:
- 试图登录路径名( docPath和defaultDBPath)。他们是否正确?
-
您已打开数据库文件,也许它不会让您复制,因此。尝试评论以下行:
returnCode = sqlite3_open(dbName,& handler);
如果(RETURNCODE!= SQLITE_OK)
NSLog(@"message---%s",sqlite3_errmsg(handler));
其他
NSLog(@"sucess---%d",returnCode);
答
考虑利用核心数据,然后使用JSON序列化的文件为您最初的有效载荷?
答
尝试下面的代码,
- (void) copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"xyz.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"XYZ.sqlite"];
}
添加-(void)CopyDatabaseIfNeeded
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
的appDelegate方法。
答
嗨我有同样的问题,因为当我将db.sqlite添加到项目捆绑我忘了检查添加到项目选项。检查此:)