rue*_*una 3 sqlite iphone fmdb ios5
要使用sqlite将数据插入数据库,需要复制数据库以使其可写.所以我在课堂上有这个方法,我在堆栈上看到的每个建议都溢出了许多其他网站:
-(void)createEditableCopyOfDatabaseIfNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
Run Code Online (Sandbox Code Playgroud)
当然我有下一个代码来访问我的数据库:
FMDatabase *db; = [FMDatabase databaseWithPath:[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"db"]];
if (![db open]) {
NSLog(@"Error!");
}
else {
NSLog(@"Database opened!!");
}
[self createEditableCopyOfDatabaseIfNeeded];
[db executeUpdate:@"Insert into user (name, phone, comment) values(?, ?, ?)", @"Name1", @"13548", @"This is a comment", nil];
NSLog(@"Inserted");
FMResultSet *s = [db executeQuery:@"SELECT * FROM user"];
while ([s next]) {
NSLog(@"%@", [s stringForColumn:@"comment"]);
}
Run Code Online (Sandbox Code Playgroud)
现在,我有几个问题:
执行/运行时,插入代码在模拟器中完美运行.但是,这对真正的sample.db没有影响,我得出结论,它必须在我的mac的硬盘驱动器中有一个可写副本.这是可以接受的.但是当我在iphone上运行这些代码时,它有点无法识别我的createEditableCopyOfDatabaseIfNeeded方法并给出了这个错误: Unknown error finalizing or resetting statement > (8: attempt to write a readonly database).如何使用FMDB使这些代码正常工作?
在iPhone上运行时,被复制的数据库位于何处?复制后,即使没有连接到我的Mac,iPhone是否会再次使用该数据库?
在设备上运行时我无法插入内容.请帮忙.
非常感谢!
如果你正在阅读这篇文章,那么我会解释你的问题.
如果Resource Bundle中有任何文件,则它是READ-ONLY文件.因此,您的资源目录的数据库路径仅供阅读之用.
根据您为复制数据库而编写的代码,将在应用程序的文档目录中创建数据库.即使从Mac上移除iPhone,此路径也不会受到影响.
| 归档时间: |
|
| 查看次数: |
5405 次 |
| 最近记录: |