Parameters.Add和Parameters.AddWithValue的区别 [英] Difference between Parameters.Add and Parameters.AddWithValue
问题描述
我读了MSDN文档和示例<一个href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx\">here我知道,对于一个 Paramters.Add
调用正确的语法是:
I read the MSDN documentation and examples here and I know that the correct syntax for a Paramters.Add
call is :
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
您必须指定参数名称,在 SqlDbType
,以 .value的
中的价值。
Where you have to specify the Parameter Name, the SqlDbType
AND the Value with .Value
.
现在的 Parameters.AddWithValue
调用正确的语法是:
Now the correct syntax for a Parameters.AddWithValue
call is :
command.Parameters.AddWithValue("@demographics", demoXml);
单行和跳过键入
部分。
我的问题是:它是如何,当我像这样做,
My Question is : How is it that when I do it like this,
command.Parameters.Add("@demographics", demoXml);
// .Add method with .AddWithValue syntax
我没有得到任何错误编译,甚至怪异,执行code时,一切似乎都正常工作?
I don't get any compiling error and even weirder, everything seems to work properly when the code is executed ?
推荐答案
有是在功能方面没有区别。事实上,无论做到这一点:
There is no difference in terms of functionality. In fact, both do this:
return this.Add(new SqlParameter(parameterName, value));
他们去precated旧赞成的理由 AddWithValue
是添加额外的清晰度,以及因为第二个参数是对象
,这使得它不会立即明显,有些人该添加
正在调用,并且他们造成了很大的不同行为。
The reason they deprecated the old one in favor of AddWithValue
is to add additional clarity, as well as because the second parameter is object
, which makes it not immediately obvious to some people which overload of Add
was being called, and they resulted in wildly different behavior.
在这个例子看看:
SqlCommand command = new SqlCommand();
command.Parameters.Add("@name", 0);
乍一看,它看起来像它调用添加(字符串名称,对象的值)
过载,的但它不是的。它调用了添加(字符串名称,SqlDbType型)
超载!这是因为0是隐式转换为枚举类型。因此,这两条线:
At first glance, it looks like it is calling the Add(string name, object value)
overload, but it isn't. It's calling the Add(string name, SqlDbType type)
overload! This is because 0 is implicitly convertible to enum types. So these two lines:
command.Parameters.Add("@name", 0);
和
command.Parameters.Add("@name", 1);
实际上导致被称为两种不同的方法。 1
不是转换为一个枚举含蓄,所以它选择了对象
超载。随着 0
,它选择的枚举超载。
Actually result in two different methods being called. 1
is not convertible to an enum implicitly, so it chooses the object
overload. With 0
, it chooses the enum overload.
这篇关于Parameters.Add和Parameters.AddWithValue的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!