Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference with Parameters.Add and Parameters.AddWithValue

Basically Commands has Parameters and parameters has functions like Add, AddWithValue, and etc. In all tutorials i've seen, i usually noticed that they are using Add instead of AddWithValue.

.Parameters.Add("@ID", SqlDbType.Int) 

vs

.Parameters.AddWithValue("@ID", 1) 

Is there a reason NOT to use AddWithValue? I'd prefer to use that over

Parameters.Add("@ID", SqlDbType.Int, 4).Value = 1 

since it saves my coding time. So which is better to use? Which is safe to use? Does it improves performance?

like image 776
John Woo Avatar asked Feb 06 '12 02:02

John Woo


People also ask

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.

What is 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.


2 Answers

With Add() method you may restrict user input by specifying type and length of data - especially for varchar columns.

.Parameters.Add("@name",SqlDbType.VarChar,30).Value=varName; 

In case of AddWithValue() (implicit conversion of value) method, it sends nvarchar value to the database.

like image 163
KV Prajapati Avatar answered Oct 14 '22 23:10

KV Prajapati


I believe there are also some cons to using AddWithValue which affect the SQL Cache Excection Plan, see the Parameter Length section here

like image 41
learnerplates Avatar answered Oct 14 '22 23:10

learnerplates