C# 与 Parameters.Add 和 Parameters.AddWithValue 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9155004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:11:02  来源:igfitidea点击:

Difference with Parameters.Add and Parameters.AddWithValue

c#.netvb.netado.net

提问by John Woo

Basically Commandshas Parametersand parameters has functions like Add, AddWithValue, and etc. In all tutorials i've seen, i usually noticed that they are using Addinstead of AddWithValue.

基本上CommandsParameters和参数有像Add,AddWithValue等的功能。在我看过的所有教程中,我通常注意到它们使用Add而不是AddWithValue.

.Parameters.Add("@ID", SqlDbType.Int)

vs

对比

.Parameters.AddWithValue("@ID", 1)

Is there a reason NOT to use AddWithValue? I'd prefer to use that over

有理由不使用AddWithValue吗?我更愿意使用它

Parameters.Add("@ID", SqlDbType.Int, 4).Value = 1

since it saves my coding time. So which is better to use? Which is safe to use? Does it improves performance?

因为它节省了我的编码时间。那么哪个更好用呢?哪个可以安全使用?它会提高性能吗?

采纳答案by adatapost

With Add()method you may restrict user input by specifying type and length of data - especially for varcharcolumns.

使用Add()方法,您可以通过指定数据的类型和长度来限制用户输入 - 特别是对于varchar列。

.Parameters.Add("@name",SqlDbType.VarChar,30).Value=varName;

In case of AddWithValue()(implicit conversion of value) method, it sends nvarchar value to the database.

AddWithValue()(值的隐式转换)方法的情况下,它将 nvarchar 值发送到数据库。

回答by Remco Ros

I'd use the AddWithValue for normal cases. And use Add(name, dbtype... only when your column type is different from how .net converts the CLR type.

我会在正常情况下使用 AddWithValue 。并且仅当您的列类型与 .net 转换 CLR 类型的方式不同时才使用 Add(name, dbtype... 。

回答by learnerplates

I believe there are also some cons to using AddWithValue which affect the SQL Cache Excection Plan, see the Parameter Length section here

我相信使用 AddWithValue 也有一些缺点会影响 SQL Cache Excection Plan,请参阅此处的参数长度部分

回答by DNQ

Using AddWithValue() adds parameter with length of current value. If the length of your parameter value varies often this means new plan is generated every time. This makes your queries run slower(additional time for parsing, compiling) and also causes higher server load.

使用 AddWithValue() 添加具有当前值长度的参数。如果您的参数值的长度经常变化,这意味着每次都会生成新计划。这会使您的查询运行速度变慢(解析、编译的额外时间)并且还会导致更高的服务器负载。