为什么我不能在SQLite中更新语句?

时间:2012-01-19 15:23:10

标签: iphone sqlite

任何人都可以帮我解决这段代码:

-(void) updateData:(NSString*)value1:(NSString*)value2
 {
    sqlite3* database;
    databaseName = @"AppDB.sqlite";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    int databaseReturnCode = sqlite3_open([databasePath UTF8String], &database);
    if(databaseReturnCode == SQLITE_OK) {

    sqlite3_stmt *updateStmt;
    const char *sql = "update PersonalInfo Set FirstName = ?,LastName = ? Where id = '1'";
    //sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL);
    sqlite3_prepare(database, sql, -1, &updateStmt,nil);

    sqlite3_bind_text(updateStmt, 1, [value1 UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(updateStmt, 2, [value2 UTF8String], -1, SQLITE_TRANSIENT);


    printf( "Update PersonalInfo| error or not an error? :  %s\n", sqlite3_errmsg(database) ); 

    while(sqlite3_step(updateStmt) == SQLITE_ROW) 
    {
        NSString *aFirstName  = [NSString stringWithUTF8String:(char *)sqlite3_column_text(updateStmt, 1)];
        NSString *aLastName  = [NSString stringWithUTF8String:(char *)sqlite3_column_text(updateStmt, 2)];


        ProfileInfo *profile = [[ProfileInfo alloc]initWithFirstName:(NSString*)aFirstName LastName:(NSString*)aLastName];
        [personalInfo addObject:profile];
        [profile release];
    }
        sqlite3_reset(updateStmt);
        sqlite3_finalize(updateStmt);
    }

}
    sqlite3_close(database);    
}

它不会进入while循环。  但是,如果我删除while循环和  将代码包含在try-catch块中,我得到了这个异常:

+[NSString stringWithUTF8String:]: NULL cString

1 个答案:

答案 0 :(得分:2)

sqlite_step while循环不适合更新语句。

来自sqlite.org的文档:

  

sqlite3_step()此例程用于评估预准备语句   之前由sqlite3_prepare()接口创建的。   该语句被评估到第一行的位置   结果可用。要进入第二行结果,请调用   sqlite3_step()再次。继续调用sqlite3_step()直到   声明完整。 不返回结果的语句(例如:   INSERT,UPDATE或DELETE语句在单个上运行完成   请致电sqlite3_step()

检查sqlite_step的返回值。它应该是SQLITE_DONE而不是SQLITE_ROW