关闭SqlConnection和SqlCommand c#

14
在我的数据访问层中,我会这样编写查询语句:
using(SQLConnection conn = "connection string here")
{
    SQLCommand cmd = new ("sql query", conn);
    // execute it blah blah
}

现在我突然想到,我没有明确关闭SQLCommand对象。我知道'using'代码块会处理SQLConnection对象,但是否也会处理SQLCommand对象?如果不是,那么我就有一个严重的问题。我需要在成千上万行代码中放置'using'代码块或在数百种方法中执行cmd.Close()。请告诉我,加入'using'代码块或关闭命令是否可以提供更好的Web应用程序内存管理?


3个回答

13

SqlConnection 不了解 SqlCommand,所以你需要自己关闭它:

using (SqlConnection conn = new SqlConnection("connection string here"))
using (SqlCommand cmd = new SqlCommand("sql query", conn))
{
    // execute it blah blah
}

10
不,using语句不会处理该命令。
您应该使用using语句包装命令,因为这样会正确调用它们的Dispose方法:
using(SQLConnection conn = 'connection string here')
{
    using(SQLCommand cmd = new ('sql query', conn))
    {
        //execute it blah blah
    }
}

5

它无法处理 SqlCommand,但是 SqlCommand 最终将由垃圾回收器处理。 我倾向于按照以下方式操作:

using (SqlConn conn ... )
using (SqlComm comm ... )
{
    conn.Open();
}

把这些using语句嵌套在一起可以同时处理两个。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接