1

我有一个使用 FMDB 作为包装器的 sqlite 数据库的 iPad 应用程序。我能够成功地从数据库中查询数据;但是,当我尝试使用 executeUpdate 插入数据时,该方法会正确触发(即我没有收到任何错误,它返回 YES),但实际上没有将任何内容插入到数据库中。我尝试立即检索我刚刚插入的对象,它为空。我还尝试查看我插入的表中的行数,并且该表为空。知道我做错了什么吗?这是一些代码:

--处理我所有数据库工作的类的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;
     }

--将我的数据库移动到文档目录的应用程序委托代码

    - (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");
    }
4

1 回答 1

1

[FMDatabase databaseWithPath:] 返回一个自动释放的对象,所以如果你不使用 ARC,你会想要保留它。

在 executeUpdate: 之后检查 [database lastError],看看它是否说明了什么。

最后 - 如果它只是一个插入,那么使用事务是没有意义的。

于 2012-06-05T17:13:50.300 回答