SQLite更新语句不起作用

时间:2013-09-17 11:44:15

标签: objective-c sqlite

我正在使用update语句来更新sqlite数据库中的记录。请帮我解决我的代码中的错误。我不明白哪里错了。我使用以下代码


sqlite3 *database;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsPath = [paths objectAtIndex:0];
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"Notes.sqlite"];
        sqlite3_stmt *updateStmt = nil;
        if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
        {
            const char *sql = [[NSString stringWithFormat:@"update Notess Set Name=? Where NoteId = %@",_notesId] UTF8String];

            if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
                NSLog(@"Error while creating update statement. %s", sqlite3_errmsg(database));
        }else{

        }
        sqlite3_bind_text(updateStmt, 1, [textVew.text  UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_finalize(updateStmt);
        sqlite3_close(database);

1 个答案:

答案 0 :(得分:2)

您在sqlite3_step声明后未能致电sqlite3_bind_text。因此,您从未真正执行过SQL。

因此,它应该看起来像:

sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"Notes.sqlite"];
sqlite3_stmt *updateStmt = nil;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
    const char *sql = [[NSString stringWithFormat:@"update Notess Set Name=? Where NoteId = %@",_notesId] UTF8String];

    if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
        NSLog(@"Error while creating update statement. %s", sqlite3_errmsg(database));

    if (sqlite3_bind_text(updateStmt, 1, [textVew.text  UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK)
        NSLog(@"Error while binding value. %s", sqlite3_errmsg(database));

    if (sqlite3_step(updateStmt) != SQLITE_DONE)
        NSLog(@"Error during step. %s", sqlite3_errmsg(database));

    sqlite3_finalize(updateStmt);
    sqlite3_close(database);
}else{
    NSLog(@"Error while opening database");
}