我们是否需要使用 SqlCommand 或者仅用于 SqlConnection 和 SqlDataReader 就足够了
我从 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 ,那么,它需要吗?
i took this code from 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));
}
}
as you can see there is no using for the SqlCommand here, so, does it needs to be ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您创建的每个实现
IDisposable
的对象都需要一个using
。其中包括SqlCommand
和SqlConnection
。这条规则很少有例外。主要的例外是 WCF 客户端代理。由于设计缺陷,它们的
Dispose
方法有时会引发异常。如果您在using
语句中使用了代理,则第二个异常将导致您丢失原始异常。You need a
using
for every object you create that implementsIDisposable
. That includes theSqlCommand
and theSqlConnection
.There are very few exceptions to this rule. The main exception is WCF client proxies. Due to a design flaw, their
Dispose
method can sometimes throw an exception. If you used the proxy in ausing
statement, this second exception would cause you to lose the original exception.您不需要需要使用 using 语句,但这是一个很好的做法,您应该使用它。它允许使用 IDisposable 自动处理对象。
http://msdn.microsoft.com/en-us /library/yh598w02(VS.80).aspx
编辑以添加链接并删除不准确的陈述,因为@John Saunders 是正确的。
You don't NEED to use a using statement, but it is good practice and you SHOULD use it. It allows objects using IDisposable to be disposed of automatically.
http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx
Edited to add link and remove inaccurate statement because @John Saunders is right.