Оператор вставки SQLite не вставляет новые данные - PullRequest
0 голосов
/ 29 апреля 2011

Оператор вставки SQLite не вставляет новые данные

я использую этот код

- (void) addN: (number *) theN
{
    const char *sql = "insert into table (valueN) Values(?)";
    sqlite3_stmt *addStmt = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * docsDir = [paths objectAtIndex:0];
        NSString * thePath = [docsDir stringByAppendingPathComponent: @"theDB.sqlite"];
        sqlite3_open([thePath UTF8String], &database);
        sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL);
        sqlite3_bind_int(addStmt, 1, theN.theNumber);
        sqlite3_step(addStmt);
        sqlite3_finalize(addStmt);
        sqlite3_close(database);
    }

и метод для вставки записи:

- (IBAction) saveN: (id) sender
{
    numbers *theNumbers = [[numbers alloc] init];
    number *theNumber = [[number alloc] init];
    theNumber.theNumber = newN;
    [theNumbers addN:theNumber];
    [theNumbers release];
    [theNumber release];
}

код выполняется, но в БД запись не вставлена. Может кто-то, пожалуйста, укажите мне, где ошибка - потому что, очевидно, есть ошибка:)

Ответы [ 2 ]

0 голосов
/ 03 мая 2011

этот код работает:

- (void) addN: (number *) theN
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *thePath = [[[NSBundle mainBundle] resourcePath]
                           stringByAppendingPathComponent:@"theDB.sqlite"];
    BOOL success = [fileManager fileExistsAtPath:thePath];
    if (!success)
    {
        NSLog(@"Failed to find database file '%@'.", thePath);
    }
    if (!(sqlite3_open([thePath UTF8String], &database) == SQLITE_OK))
    {
        NSLog(@"An error opening database, normally handle error here.");
    }
    const char *sql = "insert into table (valueN) Values(?)";
    sqlite3_stmt *addStmt = nil;
    if (sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
    {
        NSLog(@"Error, failed to prepare statement, normally handle error here.");
    }
    sqlite3_bind_int(addStmt, 1, theN.theNumber);
    sqlite3_step(addStmt);
    if(sqlite3_finalize(addStmt) != SQLITE_OK)
    {
        NSLog(@"Failed to finalize data statement, normally error handling here.");
    }
    if (sqlite3_close(database) != SQLITE_OK)
    {
        NSLog(@"Failed to close database, normally error handling here.");
    }
}
0 голосов
/ 29 апреля 2011

Вы не проверяете возвращаемые значения любого из вызовов sqlite3.Есть большая вероятность, что один из них потерпит неудачу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...