views:

137

answers:

1

Hi Guys,

I've got a problem when retrieving the primary key value of the last inserted row in the database.

I have a table of name wineDetails which contains more than 2000 wine names. I display the names in alphabetical order.

When I add a new wine name into the wineDetails table, the new wine name primary key is 2001 in the database but when I am display the wine names in alphabetic order changes I get the primary key value of another wine name instead of 2001.

To get the last inserted rows primary kay I written the code as:

- (void)addWineDetails:(wineDetails *)awineDet 
{
    sqlite3_stmt *insert_statement;
    static char *sql = "INSERT INTO wineDetails (name,regionId,categoryId) VALUES (?,?,?)";
    if (sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL) != SQLITE_OK)
    {       
        NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
    }
    sqlite3_bind_text(insert_statement, 1, [[awineDet wine_Name]UTF8String] , -1, SQLITE_TRANSIENT);
    sqlite3_bind_int(insert_statement, 2,[awineDet region_Id]);
    sqlite3_bind_int(insert_statement, 3,[awineDet category_Id]);
    int success = sqlite3_step(insert_statement);
    sqlite3_finalize(insert_statement);
    if (success == SQLITE_ERROR)
    {
        NSAssert1(0, @"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database));
    } 
    else
    {
        primaryKey = sqlite3_last_insert_rowid(database);
        int lastInsertId =  sqlite3_last_insert_rowid(database);
        wineDetPk = lastInsertId;
        printf("\n last insert id in adding:%d",lastInsertId);
        printf("\nwineDetPk id in adding:%d",wineDetPk);
    }
}

Guys please help me to get out of this.

Anyone's help wil be appreciated.

Thank you, Monish Kumar.

A: 

Last Auto ID
Is it generated by auto_increment?
If it is you can just use the insert function itself.

I also notice that you are trying to get the PK and the Insert ID. As far as I am aware the auto_increment must also be the primary key. So that it a little redundant.

If you add what the error is currently, I would be able to advice more.

Laykes
Actually I am not getting any error.But I am not gettig the result what I expected.I need to get the last Inserted row's primary key after I changed the wine names into alphabetic order.but Im not getting the last Inserted pk value,I am getting the another primary key value which was replaced after changing into alphabetic order.
monish
Guys please help me to solve this problem.
monish