创建sqlParameters的最佳实践 [英] Best Practice to create sqlParameters

查看:67
本文介绍了创建sqlParameters的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Insert into语句将值插入表中.为此,我使用了它.

I want to insert values to table using Insert into statement.For that I used it like this.

SqlCommand sqlCommand = new SqlCommand("Insert into item(itemcode,name) values (@itemcode,@itemName)");

Then I added parameters like this.
SqlParameter[] parameterList = new SqlParameter[2];

SqlParameter paraItemcode = new SqlParameter("@ItemCode", SqlDbType.Char);
paraItemcode.Value = anyValue;
parameterList[0] = paraItemcode;

SqlParameter paraName = new SqlParameter("@itemName", SqlDbType.VarChar);
paraName.Value = anyName;
parameterList[1] = paraName;

sqlCommand.Parameters.AddRange(parameterList);

Rather adding parameters like this, I can add parameters like this also
sqlCommand.Parameters.Add("@itemCode",SqlDbType.Char).Value=anyValue;
sqlCommand.Parameters.Add("@itemName",SqlDbType.VarChar).Value=anyName;


从这两种方法中,哪种方法是最佳使用方法?


From those two, which approach is the best practice to use?

推荐答案

两种方法都产生相同的结果,因此从该角度来看,两种方法都没有比这更好的方法了.另一个.第二个方法消除了必须弄乱数组的麻烦,而且冗长得多.我认为它使内容更清晰,更容易理解,这就是为什么我会选择那个.

问题可能不是如何将参数附加到命令.将数据访问隔离在一个单独的层中更为重要.在那里(只有那里)应该构造和使用命令和参数.
Both approaches produce the same result, so from that point of view none of the two is better than the other. The second one eliminates having to fumble around with an array and is far less verbose. I think it makes the clearer and easier to understand and that''s why I would go with that one.

The question might not be how to attach parameters to a command. It''s far more important to isolate data access in a separate layer. There (and only there) should commands and parameters be constructed and used.


我使用的是基于第二种方法!我发现这对我来说最有效.

因为我想创建一个可以包含许多参数的方法,所以我使用通用列表创建了该方法,因此我可以传递参数名称,值和数据类型.
I use a method based on the second one! And I find this works best for me.

Because I wanted to create a method that can have many parameters I created it using a Generic List, so I can pass Parameter Name, Value and data type.


所有方法都是相同的,并且将给你同样的结果.使用第二种方法可以节省一些代码.
您也可以使用以下方法做同样的事情

All the approaches are same and will give you the same result. Using second approach you can save some line of code.
You can do the same thing with the below approach also

SqlParameter[] param = new SqlParameter[]
{
     new SqlParameter("@itemName", 10),
     new SqlParameter("@ItemCode", "Namw")
};

sqlCommand.Parameters.AddRange(parameterList);


这篇关于创建sqlParameters的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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