区别与Parameters.Add和Parameters.AddWithValue区别、Parameters、AddWithValue、Add

2023-09-02 20:43:03 作者:艾菲尔的秘密﹌

基本上命令参数和参数有一个像添加, AddWithValue ,等在我见过的所有教程,我通常会发现,他们使用的是添加而不是 AddWithValue

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

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

VS

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

有没有理由不使用 AddWithValue ?我想preFER使用,超过

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

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?

推荐答案

通过添加()方法,你可以限制用户输入指定数据的类型和长度 - 尤其是对 VARCHAR 列。

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

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

在案件的 AddWithValue()的(隐式的值变换)方法,它发送nvarchar的值到数据库中。

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