There were 2 things I noticed in your SQL Statement, the previously mentioned lack of parameters and you had all of the inserted values single quoted- not needed for integers. Using parameters takes care of any wrapping that is needed.
The ExecuteQuery()
in JDBC would be for a SELECT query. Don't know what provider you are using, so cannot tell what this method does or returns.
Sql Server would generally use ADO, so that is what I have written this in. You would use ExecuteNonQuery()
which returns an INT representing Rows Affected. I have parameterized the query to remove the risks of Sql Injection. Notice that the catch
sets the ReturnValue to -1 so you would know if there was a failure in the method.
This table appears to be a bridge table and does not need to have a Primary Key. Due to the Foreign Key constraints, the IDs for Recipe & Drug would need to exist in their respective tables. Please note that Foreign Keys in most cases don not increase performance and are only for _Referential Integrity_; to see a performance gain you would need to have those columns indexed in this table. You could do this as a Compound Key with the two values. If you choose to make this a unique index you would need to make sure on updates that you pre-check this key to avoid a conflict.
@Eric mentioned in their answer that you may want to change the method type to void or bool. If you were to do this, I would go with bool, setting to true on success [ ReturnValue = (cmd.ExecuteNonQuery() ==1);
] and remove the portion in the catch
, so the error would domino back to the caller.
public int Save() {
int ReturnValue;
string sqlQuery = "INSERT INTO Recipe_Drug (id_recipe, id_drug, quantity, remark) VALUES (@idRecipe, @idDrug, @quantity, @remark)";
using (SqlConnection conn = new SqlConnection(ConnectionString)) {
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn)) {
cmd.Paramaters.AddWithValue("@idRecipe", Recipe.IdRecipe);
cmd.Paramaters.AddWithValue("@idDrug", Drug.IdDrug);
cmd.Paramaters.AddWithValue("@quantity", Quantity);
cmd.Paramaters.AddWithValue("@remark", Remark);
try {
conn.Open();
ReturnValue = cmd.ExecuteNonQuery();
}
catch(Exception ex) {
ReturnValue = -1;
// your error handling
}
finally { conn.Close(); }
}
}
return ReturnValue;
}