Pros and Cons of using SqlCommand Prepare in C#?
- by MadBoy
When i was reading books to learn C# (might be some old Visual Studio 2005 books) I've encountered advice to always use SqlCommand.Prepare everytime I execute SQL call (whether its' a SELECT/UPDATE or INSERT on SQL SERVER 2005/2008) and I pass parameters to it. But is it really so?
Should it be done every time? Or just sometimes?
Does it matter whether it's one parameter being passed or five or twenty?
What boost should it give if any? Would it be noticeable at all (I've been using SqlCommand.Prepare here and skipped it there and never had any problems or noticeable differences).
For the sake of the question this is my usual code that I use, but this is more of a general question.
public static decimal pobierzBenchmarkKolejny(string varPortfelID, DateTime data, decimal varBenchmarkPoprzedni, decimal varStopaOdniesienia) {
const string preparedCommand = @"SELECT [dbo].[ufn_BenchmarkKolejny](@varPortfelID, @data, @varBenchmarkPoprzedni, @varStopaOdniesienia) AS 'Benchmark'";
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP)) //if (varConnection != null) {
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection)) {
sqlQuery.Prepare();
sqlQuery.Parameters.AddWithValue("@varPortfelID", varPortfelID);
sqlQuery.Parameters.AddWithValue("@varStopaOdniesienia", varStopaOdniesienia);
sqlQuery.Parameters.AddWithValue("@data", data);
sqlQuery.Parameters.AddWithValue("@varBenchmarkPoprzedni", varBenchmarkPoprzedni);
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
while (sqlQueryResult.Read()) {
//sqlQueryResult["Benchmark"];
}
}
}
}