Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlCommand Parameters Add vs. AddWithValue [duplicate]

When should I use Parameters. Add/AddWithValue? In the following MSDN example they use Parameters.Add for int and Parameters.AddWithValue for string

command.Parameters.Add("@ID", SqlDbType.Int); command.Parameters["@ID"].Value = customerID;  command.Parameters.AddWithValue("@demographics", demoXml); 

What is the best to use for datetime

like image 611
Yakov Avatar asked Jan 14 '14 09:01

Yakov


People also ask

What is Sqlcommand parameters AddWithValue?

AddWithValue replaces the SqlParameterCollection. Add method that takes a String and an Object. The overload of Add that takes a string and an object was deprecated because of possible ambiguity with the SqlParameterCollection.

What is the difference between ADD and AddWithValue?

Add overload that takes a String and a SqlDbType enumeration value where passing an integer with the string could be interpreted as being either the parameter value or the corresponding SqlDbType value. Use AddWithValue whenever you want to add a parameter by specifying its name and value.


1 Answers

Use Add if you want to make all explicit with a little bit more work. Use AddWithValue if you are lazy. AddWithValue will derive the type of the parameter of its value, so ensure that it's the correct type. You should, for example, parse a string to int if that is the correct type.

There is one reason to avoid Add: if your parameter type is int you must be careful with the overload that takes the parameter-name and an object since then another overload is chosen with the SqlDbType-enum.

From remarks (method overload is even obsolete now):

Use caution when you are using this overload of the SqlParameterCollection.Add method to specify integer parameter values. Because this overload takes a value of type Object, you must convert the integral value to an Object type when the value is zero ... If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameterCollection.Add(string, SqlDbType) overload.

like image 190
Tim Schmelter Avatar answered Oct 03 '22 14:10

Tim Schmelter