Cannot Retrieve Value From Last Insert Row in SQL Database
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, @"Erro开发者_如何学Gor: 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.
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.
精彩评论