Does SqlCommand.Dispose close the connection?(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 是否关闭连接?


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01