是否SqlCommand.Dispose关闭连接?SqlCommand、Dispose

2023-09-02 20:43:49 作者:手心里の嗳

我能否有效地使用这种方法?

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一个使用块,以及

No, Disposing of the Command will not effect the Connection. A better approach would be to also wrap the SqlCommand 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.

因此,在处理命令的绝对不处理它使用的连接。的

So, disposing of the command definitely does not dispose of the connection it was using.