SqlCommand.Dispose 是否关闭连接?

2023-12-12

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

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 对象?


不,处置SqlCommand不会影响连接。更好的方法是将SqlConnection也在 using 块中:

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

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

EDIT:

我刚刚测试了这个:

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 块时,第一个命令被处理。连接仍然打开并且适合第二个命令。

因此,处置该命令绝对不会处置它正在使用的连接。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SqlCommand.Dispose 是否关闭连接? 的相关文章

随机推荐