When querying the database with the same query but different parameters, is it better to:
- do it in a single using,
- or to create two separate queries?
Example of a single using:
using (SqlCommand addProduct = new SqlCommand(@"insert into [Products].[Products] ([Name], [Price]) values (@name, @price)", sqlConnection))
{
// Insert the first product.
addProduct.Parameters.AddWithValue("@name", "Product 1");
addProduct.Parameters.AddWithValue("@price", 41F);
int countAffectedRows = addProduct.ExecuteNonQuery();
Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
addProduct.Parameters.Clear();
// Insert the second product.
addProduct.Parameters.AddWithValue("@name", "Product 2");
addProduct.Parameters.AddWithValue("@price", 49.9);
countAffectedRows = addProduct.ExecuteNonQuery();
Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
}
Example of the same code using two separate queries:
// Insert the first product.
using (SqlCommand addProduct = new SqlCommand(@"insert into [Products].[Products] ([Name], [Price]) values (@name, @price)", sqlConnection))
{
addProduct.Parameters.AddWithValue("@name", "Product 1");
addProduct.Parameters.AddWithValue("@price", 41F);
int countAffectedRows = addProduct.ExecuteNonQuery();
Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
}
// Insert the second product.
using (SqlCommand addProduct = new SqlCommand(@"insert into [Products].[Products] ([Name], [Price]) values (@name, @price)", sqlConnection))
{
addProduct.Parameters.AddWithValue("@name", "Product 2");
addProduct.Parameters.AddWithValue("@price", 49.9);
int countAffectedRows = addProduct.ExecuteNonQuery();
Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
}
In my opinion, the second one must be preferred, because:
- it makes it more clear to see where the SQL command is disposed and how much times it is executed,
- it is easier to modify if, in future, for some reason, the query must be modified in one case, but not in the other,
- the first one makes it easy to forget the
SqlCommand.Parameters.Clear()
.
On the other hand, the first sample is more explicit about the fact that the query is the same in both cases, and that only parameters change.