SqlCommand.Dispose是否关闭连接?

And*_*nea 51 .net garbage-collection dispose sqlcommand sqlconnection

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

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

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

Rya*_*ley 108

不,处置SqlCommand不会影响连接.更好的方法是将for包装SqlConnection在一个使用块中:

using (SqlConnection conn = new SqlConnection(connstring))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand(cmdstring, conn))
    {
        cmd.ExecuteNonQuery();
    }
}
Run Code Online (Sandbox Code Playgroud)

否则,由于正在使用它的Command被处理掉(也许这就是你想要的?),Connection就不会改变.但请记住,连接也应该被处理掉,并且处理命令可能比命令更重要.

编辑:

我刚试过这个:

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();  
Run Code Online (Sandbox Code Playgroud)

退出使用块时放置第一个命令.连接仍然是开放的,对第二个命令很有用.

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

  • 该示例的要点不是显示更简单的语法,而是为了演示两个SqlCommands可以与相同的连接一起使用,然后在不丢弃连接的情况下进行处理.需要打开连接然后再使用两次才能证明这一点(参见原始问题). (7认同)

小智 10

SqlCommand.Dispose是不够的,因为许多SqlCommand可以(重新)使用相同的SqlConnection.将重点放在SqlConnection上.