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 是否关闭连接?
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
