SQLite 数据库无法正常工作

SQLite Database not working correctly

我正在尝试将一些数据保存在我的 iOS 应用程序的 SQLite 数据库中。我正在使用以下方法执行此操作:

NSString *query = [NSString stringWithFormat:@"INSERT INTO categories VALUES ('%@', '%@', '%@', null, %d)", categoryName, @"test", @"test", 33];

NSLog(@"Query is: %@", query);

[[AFSQLManager sharedManager]performQuery:query withBlock:^(NSArray *row, NSError *error, BOOL finished) {

    if (!error) {

        if (!finished) {
            NSLog(@"No success");
        } else {
            NSLog(@"Succeeded");
        }
     } else {

         UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Oops" message:error.description delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alertView show];
     }
}];

而这个是打开数据库的方法,在viewDidLoad中执行:

[[AFSQLManager sharedManager]openLocalDatabaseWithName:@"test.sqlite" andStatusBlock:^(BOOL success, NSError *error) {
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Oops" message:error.description delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }
}];

如您所见,我使用 AFSQLManager 执行查询(您可以在此处找到它 https://github.com/AlvaroFranco/AFSQLManager)。上面的方法记录 'succeeded',但是当我从数据库中提取一些数据时,我没有得到任何结果。我最好的猜测是 SQLite 数据库有问题....知道我做错了什么吗?

您引用的 class 在其打开例程中有一个相当基本的问题,即它从包中打开数据库:

-(void)openLocalDatabaseWithName:(NSString *)name andStatusBlock:(statusBlock)status {

    NSString *path = [[NSBundle mainBundle]pathForResource:[[name lastPathComponent]stringByDeletingPathExtension] ofType:[name pathExtension]];

    if (sqlite3_open([path UTF8String], &_database) != SQLITE_OK) {
        NSLog(@"Failed to open database!");
        status(NO, nil);
    } else {
        NSLog(@"Database opened properly");
        status(YES, nil);
    }
}

捆绑包是只读的。因此,任何更新该数据库中数据的尝试都将失败。

如果要更新数据库,则必须先将数据库复制到 Documents 文件夹(或缓存或临时文件夹或其他文件夹)(或在其中创建数据),然后再尝试打开它。