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

查看:25
本文介绍了SqlCommand 参数 Add 与 AddWithValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候应该使用参数.添加/AddWithValue?在下面的 MSDN 示例中,他们使用 Parameters.Add 作为 intParameters.AddWithValue 作为 string

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

datetime

推荐答案

使用 Add 如果您想通过更多的工作使所有内容变得明确.如果您很懒惰,请使用 AddWithValue.AddWithValue 将派生其值的参数类型,因此请确保它是正确的类型.例如,如果类型正确,您应该将 string 解析为 int.

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 its value, so ensure that it's the correct type. You should, for example, parse a string to int if that is the correct type.

避免 Add 的原因之一是:如果您的参数类型是 int,则必须小心使用 重载采用参数名称和对象 从那时起使用SqlDbType-enum<选择了另一个重载.

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 (method overload is even obsolete now):

在使用此重载时要小心SqlParameterCollection.Add 方法指定整数参数值.由于此重载采用 Object 类型的值,因此您必须转换当值为零时对象类型的整数值... 如果您不执行此转换,则编译器假定您正在尝试调用SqlParameterCollection.Add(string, SqlDbType) 重载.

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 ... If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameterCollection.Add(string, SqlDbType) overload.

这篇关于SqlCommand 参数 Add 与 AddWithValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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