Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More Efficient Way of Adding Parameters to a SqlCommand .NET

Tags:

.net

sql

I was just reading a question about how to add parameters to a SqlCommand in .NET, and it raised a question for me. In all of my programs, this is how I add parameters to my commands:

SqlCommand cmd = new SqlCommand(cmdText,conn);
cmd.Parameters.Add(new SqlParameter("@name",value));

I know that you can also add parameters in the following way:

cmd.Parameters.Add(name, dbType, size).Value = value;

Which of these methods of adding parameters is better? Does it matter? I know that using the Sql namespaces is more efficient with SQL Server queries, so my first response would be that using the SqlParameter would be more efficient. However, since it's already a SqlCommand, I'm not quite sure about that. Also, since using the SqlParameter instantiates a new object, could that make it less efficient than the other case?

like image 886
Aaron Avatar asked Dec 10 '22 17:12

Aaron


2 Answers

Both ways are going to create objects - whether you call the constructor yourself or whether another method does, the object is still going to be created.

More importantly, however, you're about to make a database call. The cost of creating a dozen objects is going to be absolutely peanuts compared with the database call, even if it's a very fast call.

Don't worry about it - just use the most readable code.

like image 193
Jon Skeet Avatar answered Mar 23 '23 20:03

Jon Skeet


This is how I am doing it in code:

cmd.Parameters.AddWithValue("@name", value);
like image 20
Nathen Silver Avatar answered Mar 23 '23 19:03

Nathen Silver