我从 msdn 中获取了这段代码
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
如您所见,这里没有使用 SqlCommand,那么,它需要吗?
最佳答案
您创建的每个实现IDisposable
的对象都需要一个using
。这包括 SqlCommand
和 SqlConnection
。
这条规则几乎没有异常(exception)。主要的异常(exception)是 WCF 客户端代理。由于设计缺陷,他们的 Dispose
方法有时会抛出异常。如果您在 using
语句中使用代理,则第二个异常会导致您丢失原始异常。
关于c# - 我们需要使用 SqlCommand 还是仅用于 SqlConnection 和 SqlDataReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2252062/