SqlCommand.Dispose 是否关闭连接?

Does SqlCommand.Dispose close the connection?(SqlCommand.Dispose 是否关闭连接?)

本文介绍了SqlCommand.Dispose 是否关闭连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以有效地使用这种方法吗?

Can I use this approach efficiently?

using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString))
{
    cmd.Connection.Open();
    // set up parameters and CommandType to StoredProcedure etc. etc.
    cmd.ExecuteNonQuery();
}

我关心的是:SqlCommand 的 Dispose 方法(退出 using 块时调用)是否会关闭底层的 SqlConnection 对象?

My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?

推荐答案

不,处理 SqlCommand 不会影响连接.更好的方法是将 SqlConnection 也包装在 using 块中:

No, Disposing of the SqlCommand will not effect the Connection. A better approach would be to also wrap the SqlConnection in a using block as well:

using (SqlConnection conn = new SqlConnection(connstring))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand(cmdstring, conn))
    {
        cmd.ExecuteNonQuery();
    }
}

否则,连接不会因为使用它的命令被释放(也许这就是你想要的?)而改变.但请记住,连接应该也会被处理掉,而且处理起来可能比命令更重要.

Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should be disposed of as well, and likely more important to dispose of than a command.

我刚刚测试了这个:

SqlConnection conn = new SqlConnection(connstring);
conn.Open();

using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 1", conn))
{
    Console.WriteLine(cmd.ExecuteScalar().ToString());
}

using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 2", conn))
{
    Console.WriteLine(cmd.ExecuteScalar().ToString());
}

conn.Dispose();  

退出 using 块时释放第一个命令.连接仍然打开并且对第二个命令有好处.

The first command was disposed when the using block was exited. The connection was still open and good for the second command.

因此,释放命令肯定不会释放它正在使用的连接.

这篇关于SqlCommand.Dispose 是否关闭连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:SqlCommand.Dispose 是否关闭连接?

基础教程推荐