我有一个使用FMDB作为包装的sqlite数据库的iPad应用程序。我能够成功地从数据库中查询数据;但是,当我尝试使用executeUpdate插入数据时,该方法正确触发(即我没有错误并返回YES)但实际上没有任何内容插入到数据库中。我尝试立即检索刚刚插入的对象,它为null。我还试着查看我插入的表中的行数,表是空的。知道我做错了什么吗?这是一些代码:
- 处理我所有数据库工作的类的init方法
-(NSString *)getDbPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"iRecipeBox.db"];
}
-(id)init {
self = [super init];
if(self) {
database = [FMDatabase databaseWithPath:[self getDbPath]];
[database open];
}
return self;
}
- 将我的数据库移动到docs目录的应用委托代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *docsPath = [documentsDirectory stringByAppendingPathComponent:@"iRecipeBox.db"];
if ([fileManager fileExistsAtPath:docsPath] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"iRecipeBox" ofType:@"db"];
[fileManager copyItemAtPath:resourcePath toPath:docsPath error:&error];
}
return YES;
}
- 将数据插入其中一个表的代码
recipeID = [NSNumber numberWithInt:newRecipeID];
[database beginTransaction];
NSArray *newRow = [[NSArray alloc] initWithObjects:recipeID,title, description, picFile, prepTime, cookTime, ovenTemp, nil];
NSString *sql = @"insert into recipes (id, name, descr, picFile, prepTime, cookTime, ovenTemp) values (?, ?, ?, ?, ?, ?, ?)";
NSLog(@"Before update, the number of args is %i", [newRow count]);
if([database executeUpdate:sql withArgumentsInArray:newRow]) {
[database commit];
NSLog(@"the insert worked");
} else {
[database rollback];
NSLog(@"the insert failed");
}
答案 0 :(得分:1)
[FMDatabase databaseWithPath:]返回一个自动释放的对象,因此如果您不使用ARC,则需要保留该对象。
在executeUpdate:之后立即检查[database lastError],看看它是否显示任何内容。
最后 - 如果它只是一个插入,那么使用交易毫无意义。