关闭的SqlConnection和SqlCommand的C#
问题描述:
在我DAL我编写查询这样的:关闭的SqlConnection和SqlCommand的C#
using(SQLConnection conn = "connection string here")
{
SQLCommand cmd = new ("sql query", conn);
// execute it blah blah
}
现在它只是发生在我身上,我没有显式关闭SqlCommand对象。现在我知道“使用”块将处理SQLConnection对象,但这是否也会照顾SQLCommand对象?如果不是,我有一个严重的问题。我必须在成千上万行代码中使用SQLCommand中的“使用”,或者对数百种方法执行cmd.Close()。请告诉我,如果使用或关闭命令将提供更好的Web应用程序的内存管理?
答
不,using
声明不会处理该命令。
你应该换用using
语句命令为好,因为这会正确地调用Dispose
他们:
using(SQLConnection conn = 'connection string here')
{
using(SQLCommand cmd = new ('sql query', conn))
{
//execute it blah blah
}
}
答
的SqlConnection
没有关于SqlCommand
知识,所以你应该自行关闭:
using (SqlConnection conn = new SqlConnection("connection string here"))
using (SqlCommand cmd = new SqlCommand("sql query", conn))
{
// execute it blah blah
}
答
它不会处理SqlCommand
,但SqlCommand
将最终由垃圾收集处理。我倾向于执行以下操作:
using (SqlConn conn ...)
using (SqlComm comm ...)
{
conn.Open();
}
堆栈使用语句在这里将处理这两个。
我想这也应该是有趣的你:http://valueinjecter.codeplex.com/ WIKIPAGE?标题=数据%20access%20layer%20%28ORM%29%20with%第二十条%20Value%20Injecter&referringTitle =首页 – Omu 2010-07-30 11:37:55