的SqlCommand参数添加与AddWithValue [英] SqlCommand Parameters Add vs. AddWithValue
问题描述
当我应该使用参数。添加/ AddWithValue
?
在下面的例子MSDN他们使用 Parameters.Add
为 INT
和 Parameters.AddWithValue
为字符串
command.Parameters.Add(@ ID,SqlDbType.Int);
command.Parameters [@ ID]值=的customerID。command.Parameters.AddWithValue(@人口统计,demoXml);
什么是最好的用于日期时间
使用添加
如果你想使所有多一点的工作明确。使用 AddWithValue
如果你是懒惰。 AddWithValue
将获得它的值的参数的类型,因此请确保它是正确的类型。你应该例如解析字符串
到 INT
如果这是正确的类型。
有一个理由,以避免添加
,如果你的参数类型 INT
你必须小心与< A HREF =http://msdn.microsoft.com/en-us/library/9dd8zze1%28v=vs.110%29.aspx>过载,是以参数名,此后一个目的 < A HREF =http://msdn.microsoft.com/en-us/library/wbys3e9s%28v=vs.110%29.aspx>另一个超载选择与 SqlDbType
-enum 。
通过言论:
当您使用的此重载使用注意事项
SqlParameterCollection.Add方法来指定整数参数值。
由于这种重载接受Object类型的值,必须转换
的积分值到对象类型时的值为零,当
下面的C#示例演示。
块引用>parameters.Add(@ PNAME,Convert.ToInt32(0));
如果您不执行此转换,
编译器假设你正试图调用
SqlParameterCollection.Add(字符串,SqlDbType)过载。
块引用>When should I use
Parameters. Add/AddWithValue
? In the following MSDN example they useParameters.Add
forint
andParameters.AddWithValue
forstring
command.Parameters.Add("@ID", SqlDbType.Int); command.Parameters["@ID"].Value = customerID; command.Parameters.AddWithValue("@demographics", demoXml);
What is the best to use for
datetime
解决方案Use
Add
if you want to make all explicit with a little bit more work. UseAddWithValue
if you are lazy.AddWithValue
will derive the type of the parameter of it's value, so ensure that it's the correct type. You should for example parse astring
toint
if that is the correct type.There is one reason to avoid
Add
, if your parameter type isint
you must be careful with the overload that takes the parameter-name and an object since then another overload is chosen with theSqlDbType
-enum.From remarks:
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, as the following C# example demonstrates.
parameters.Add("@pname", Convert.ToInt32(0));
If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameterCollection.Add (string, SqlDbType) overload.
这篇关于的SqlCommand参数添加与AddWithValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!