×
您的位置: 首页 > 编程笔记

Parameters.Add和Parameters.AddWithValue的区别(Difference between Parameters.Add and Parameters.AddWithVa

C# 时间:2020-06-19  查看:0   收藏

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;

Where you have to specify the Parameter Name, the SqlDbType AND the Value with .Value.

Now the correct syntax for a Parameters.AddWithValue call is :

   command.Parameters.AddWithValue("@demographics", demoXml);

Single line and skip the Type part.

My Question is : How is it that when I do it like this,

   command.Parameters.Add("@demographics", demoXml);
   // .Add method with .AddWithValue syntax

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));

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.

Take a look at this example:

 SqlCommand command = new SqlCommand();
 command.Parameters.Add("@name", 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);

and

 command.Parameters.Add("@name", 1);

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.

我读了MSDN文档和示例here我知道,对于一个 Paramters.Add 调用正确的语法是:

  command.Parameters.Add(@ ID,SqlDbType.Int);
   command.Parameters [@ ID]值=的customerID。

您必须指定参数名称,在 SqlDbType ,以 .value的中的价值。

现在的 Parameters.AddWithValue 调用正确的语法是:

  command.Parameters.AddWithValue(@人口统计,demoXml);

单行和跳过键入部分。

我的问题是:它是如何,当我像这样做,

  command.Parameters.Add(@人口统计,demoXml);
   //。新增法.AddWithValue语法

我没有得到任何错误编译,甚至怪异,执行code时,一切似乎都正常工作?


解决方案

有是在功能方面没有区别。事实上,无论做到这一点:

 返回this.Add(新的SqlParameter(参数名称,值));

他们去precated旧赞成的理由 AddWithValue 是添加额外的清晰度,以及因为第二个参数是对象,这使得它不会立即明显,有些人该添加正在调用,并且他们造成了很大的不同行为。

在这个例子看看:

 的SqlCommand命令=新的SqlCommand();
 command.Parameters.Add(@名,0);

乍一看,它看起来像它调用添加(字符串名称,对象的值)过载,的但它不是的。它调用了添加(字符串名称,SqlDbType型)超载!这是因为0是隐式转换为枚举类型。因此,这两条线:

  command.Parameters.Add(@名,0);

  command.Parameters.Add(@名,1);

实际上导致被称为两种不同的方法。  1 不是转换为一个枚举含蓄,所以它选择了对象超载。随着 0 ,它选择的枚举超载。

 

0% (0)
0% (0)