【发布时间】:2017-08-01 15:24:38
【问题描述】:
我连接到这样设置的数据库以调用存储过程。我只是想知道这是否是最好的方法。 我有两个 using 语句,一个用于 sqlConnection,一个用于 sqlCommand(我不确定是否需要)
using (SqlConnection con1 = new SqlConnection(conString1))
{
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.Connection = con1;
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.CommandText = "updateVendorEstNo";
cmd1.Parameters.AddWithValue("@plantNameNew", vPlantName.Value.ToString().Trim());
var result = cmd1.Parameters.Add("@result", SqlDbType.Int);
result.Direction = ParameterDirection.Output;
var resultDesc = cmd1.Parameters.Add("@resultDesc", SqlDbType.VarChar, 100);
resultDesc.Direction = ParameterDirection.Output;
con1.Open(); // open connection
cmd1.ExecuteNonQuery();
res = result.Value.ToString().Trim();
resDesc = resultDesc.Value.ToString().Trim();
}
}
我最大的问题是我在做什么:
using (SqlCommand cmd1 = new SqlCommand())
现在做的方式还好吗..还是应该更像,
using (SqlCommand cmd1 = new SqlCommand("updateVendorEstNo",con1))
【问题讨论】:
-
任何一种方式都可以——如果你测试过,你就会知道。只需选择您最喜欢的一个。是的,您几乎应该总是将实现 IDisposable 的对象包装在 using 语句中。
-
应该不会对
using语句产生任何影响。它将在这两种情况下继续工作。唯一的区别是构造函数调用,应该没有任何影响。 -
我确实测试过。两种方式都有效..但如果一个更好的性能明智的话,我不是。
-
唯一真正的区别是可读性。
SqlCommand包含在using块中。如果您运行多个SqlCommands,为了清楚起见,我会将命令文本留在using块语句之外,但如果只运行一个命令,我倾向于将其包含在using行中。我认为这主要是个人喜好问题。 -
@psj01 然后对其进行基准测试。
标签: c# sqlconnection sqlcommand