的SqlCommand参数添加与AddWithValue [英] SqlCommand Parameters Add vs. AddWithValue

查看:342
本文介绍了的SqlCommand参数添加与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 =htt​​p://msdn.microsoft.com/en-us/library/9dd8zze1%28v=vs.110%29.aspx>过载,是以参数名,此后一个目的 < A HREF =htt​​p://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 use Parameters.Add for int and Parameters.AddWithValue for string

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. Use AddWithValue 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 a string to int if that is the correct type.

There is one reason to avoid Add, if your parameter type is int you must be careful with the overload that takes the parameter-name and an object since then another overload is chosen with the SqlDbType-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆