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 是否关闭连接?


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01