SQLite3数据库实际上并没有插入数据 - iPhone

Mis*_*Moo 5 sqlite iphone objective-c

我正在尝试在我的数据库中添加一个新条目,但它不起作用.没有抛出错误,并且应该在插入运行后执行的代码,这意味着查询没有错误.但是,数据库中没有添加任何内容.我已经尝试了两个预处理语句和更简单的sqlite3_exec,结果相同.

我知道我的数据库正在加载,因为tableview(和后续的tableviews)的信息是从数据库加载的.连接不是问题.

此外,sqlite3_last_insert_rowid(db)的日志返回下一行的正确数字.但是,信息仍未保存.

这是我的代码:

db = [Database openDatabase];           
NSString *query = [NSString stringWithFormat:@"INSERT INTO lists (name) VALUES('%@')", newField.text];
NSLog(@"Query: %@",query);

sqlite3_stmt *statement;

if (sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
  if (sqlite3_step(statement) == SQLITE_DONE){
    NSLog(@"You created a new list!");
    int newListId = sqlite3_last_insert_rowid(db);
    MyList *newList = [[MyList alloc] initWithName:newField.text idNumber:[NSNumber numberWithInt:newListId]];
    [self.listArray addObject:newList];
    [newList release];
    [self.tableView reloadData];
    sqlite3_finalize(statement);
  }
  else {
    NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(db));
  }
}
[Database closeDatabase:db];
Run Code Online (Sandbox Code Playgroud)

同样,没有抛出任何错误.prepare和step语句分别返回SQLITE_OK和SQLITE_DONE,但没有任何反应.

任何帮助表示赞赏!

Mat*_*ang 7

确保已将数据库移动到可写目录,例如NSDocumentDirectoryNSLibraryDirectory.

您在XCode中看到的数据库文件位于MainBunble可读但不可写的文件中.

如果数据库存在于已决定(可写)的位置,则需要添加一个在运行时检查的方法,如果该数据库不存在,则使用NSFileManager该方法将数据库文件复制到可写目录路径.

这是我的应用程序Snap-it Notes的一个片段:

+ (BOOL)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
    BOOL newInstallation;
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"database_file_path"];
    success = [fileManager fileExistsAtPath:writableDBPath];
    newInstallation = !success;
    if (success) {
        [fileManager release];
        return newInstallation;
    }
    // The writable database does not exist, so copy the default to the appropriate location.
    //NSLog(@"database does not exist");
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database_file_path"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    [fileManager release];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
    return newInstallation;
}
Run Code Online (Sandbox Code Playgroud)