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.