SQLite insert语句不插入新数据

时间:2011-04-29 13:01:02

标签: objective-c

SQLite insert语句不插入新数据

我正在使用此代码

- (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];
}

执行代码,但DB中没有插入记录。 有人可以指出我错在哪里 - 因为显然有一个错误:)

2 个答案:

答案 0 :(得分:0)

您没有检查任何sqlite3调用的返回值。他们中的一个很有可能失败了。

答案 1 :(得分:0)

此代码似乎有效:

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