Quando interrogare il database con la stessa query, ma diversi parametri, è meglio:È meglio riutilizzare SqlCommand quando si esegue la stessa query SQL più volte?
- lo fanno in un unico utilizzando,
- o per creare due query separate?
Esempio di un singolo utilizzando:
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.");
}
esempio dello stesso codice utilizzando due query separate:
// 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.");
}
A mio parere, il secondo deve essere preferito , perché:
- rende più chiaro vedere dove viene disposto il comando SQL e quante volte viene eseguito,
- è più facile da modificare se, in futuro, per qualche motivo, la query deve essere modificata in un caso, ma non nell'altro,
- il primo rende facile dimenticare lo
SqlCommand.Parameters.Clear()
.
D'altra parte, il primo esempio è più esplicito sul fatto che la query è la stessa in entrambi i casi e che solo i parametri cambiano.
Hai ragione, la seconda soluzione è più pulita. Non si dovrebbe riutilizzare lo stesso SqlCommand a meno che non si abbia intenzione di eseguire un hyper-mega tuning delle prestazioni. – Davita
Forse dovresti inserire il codice inserto in una funzione separata e chiamarlo due volte. –