SqlCommand 参数 Add 与 AddWithValue [重复]
Posted
技术标签:
【中文标题】SqlCommand 参数 Add 与 AddWithValue [重复]【英文标题】:SqlCommand Parameters Add vs. AddWithValue [duplicate] 【发布时间】:2014-02-02 07:16:53 【问题描述】:什么时候应该使用Parameters. Add/AddWithValue
?
在下面的 MSDN 示例中,他们使用 Parameters.Add
表示 int
和 Parameters.AddWithValue
表示 string
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
command.Parameters.AddWithValue("@demographics", demoXml);
datetime
最好用什么
【问题讨论】:
cmd.Parameters.Add
is deprecated now. Instead use cmd.Parameters.AddWithValue
@RahulNikate 正如下面的 Bacon Bits 所述,“cmd.Parameters.Add(String, SqlDbType) 未被弃用。仅 cmd.Parameters.Add(String, Object) 被弃用(现已过时)。 "
事实上,SQL 专家最近的趋势(搜索文章的相关关键字)似乎更倾向于使用 Add(String, SqlDBType) 并由于数据类型模糊导致效率低下而放弃 AddWithValue。 (是的,这个问题很古老......但我现在在这里!)
【参考方案1】:
如果您想通过更多工作使所有内容变得明确,请使用Add
。如果您很懒,请使用AddWithValue
。 AddWithValue
将导出其值的参数类型,因此请确保它是正确的类型。例如,您应该将 string
解析为 int
(如果这是正确的类型)。
避免使用Add
的原因之一:如果您的参数类型是int
,那么您必须小心overload that takes the parameter-name and an object,从那时起another overload is chosen with the SqlDbType
-enum。
来自remarks(现在方法重载甚至是obsolete
):
当你使用这个重载的
SqlParameterCollection.Add
方法指定整数参数值。 由于此重载采用 Object 类型的值,因此您必须转换 值为零时对象类型的整数值 ... 如果您不执行此转换,则 编译器假定您正在尝试调用SqlParameterCollection.Add(string, SqlDbType)
过载。
【讨论】:
cmd.Parameters.Add
is deprecated now. Instead use cmd.Parameters.AddWithValue
@RahulNikate: AddWithValue
也不是最好的方法,因为它从参数值推断参数的类型。这通常会导致错误的执行计划或不正确的转换。它也不会首先验证参数(例如,键入 if Datetime
但您传递了 String
)。只有Add(String parameterName, Object value)
不推荐使用Add
的所有其他重载。我更喜欢带有参数名称和SqlDbType
的那个(如果是字符串类型,请考虑指定大小)。
AddWithValue
只是避免了我的回答中提到的问题,并且具有与Add(string, object)
相同的功能。
我不同意 Add 比 AddWithValue 更好——他们都可能犯错误——所以使用哪个更简单。 Add 可用于提前设置参数,以便您只需要指定对象。另外,这个Parameters.Add("@BEGDATE", SqlDbType.DateTime).Value = myDate
。几乎和 AddWithValue 一样短。
请注意cmd.Parameters.Add(String, SqlDbType)
is not deprecated。仅限cmd.Parameters.Add(String, Object)
is deprecated (now obsolete)。以上是关于SqlCommand 参数 Add 与 AddWithValue [重复]的主要内容,如果未能解决你的问题,请参考以下文章
为啥“nvarchar”参数比“文本”“SqlCommand”命令的其他类型更快?