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
Difference with Parameters.Add and Parameters.AddWithValue
提问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.
基本上Commands有Parameters和参数有像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
回答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() 添加具有当前值长度的参数。如果您的参数值的长度经常变化,这意味着每次都会生成新计划。这会使您的查询运行速度变慢(解析、编译的额外时间)并且还会导致更高的服务器负载。

