Pros and Cons of using SqlCommand Prepare in C#?
Posted
by MadBoy
on Stack Overflow
See other posts from Stack Overflow
or by MadBoy
Published on 2010-03-15T19:23:16Z
Indexed on
2010/03/15
19:29 UTC
Read the original article
Hit count: 277
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"];
}
}
}
}
© Stack Overflow or respective owner