I insert a value into a SQLite database and return the id of the last inserted value as a result of the method.
I asked a question on Stackoverflow and I found this solution to my problem. Now I would like to get feedback if there is a simpler, smarter and/or safer way to do that:
int MyRepository::Insert(std::shared_ptr<MyObject> myObject)
{
if(myObject == nullptr) { return -1; }
sqlite3_exec(_connection, "BEGIN TRANSACTION;", NULL, NULL, NULL);
std::string query = R"(
INSERT INTO myObject (EquipmentId, ExerciseId ) VALUES (?1, ?2);
)";
int lastInsertedId = -1;
sqlite3_stmt* sqlStatement;
sqlite3_prepare_v2(_connection, query.c_str(), -1, &sqlStatement, nullptr);
sqlite3_bind_int (sqlStatement, 1, myObject->GetEquipmentId());
sqlite3_bind_int (sqlStatement, 2, myObject->GetExerciseId() );
int returnCode = sqlite3_step(sqlStatement);
if (returnCode != SQLITE_DONE)
{
throw SqliteException(returnCode, std::string(sqlite3_errmsg(_connection)));
}
query = "SELECT last_insert_rowid()";
returnCode = sqlite3_prepare_v2(_connection, query.c_str(), -1, &sqlStatement, NULL);
if (returnCode != SQLITE_OK)
{
throw SqliteException(returnCode, std::string(sqlite3_errmsg(_connection)));
}
returnCode = sqlite3_step(sqlStatement);
if(returnCode == SQLITE_ROW)
{
lastInsertedId = sqlite3_column_int(sqlStatement, 0);
}
sqlite3_exec(_connection, "COMMIT;", NULL, NULL, NULL);
sqlite3_finalize(sqlStatement);
return lastInsertedId;
}