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 是否关闭连接?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30