c# - .Net : Does my connection get closed via Dispose in this example?

标签 c# ado.net

这是我的示例的简化版本:

using (DbCommand cmd = new SqlCommand("myProcedure", (SqlConnection)DataAccessHelper.CreateDatabase().CreateConnection()) { CommandType = CommandType.StoredProcedure })
{
    cmd.Connection.Open();
    using(IDataReader dr = cmd.ExecuteReader())
        doWork(dr);
}

当命令被释放时,连接是否关闭?或者我是否需要先使用 using 语句用于连接,然后在闭包中创建命令?

最佳答案

如果想让读者关闭连接,可以使用ExecuteReader()的重载:

...
using (IDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) 
...

默认情况下,处置阅读器不会释放连接。 - see MSDN for more info...

为了解决 Close()Dispose() 的问题,MSDN 指出:

If the DbConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close or Dispose, which are functionally equivalent.

因此不一定需要设置自闭连接。主要区别在于可以重新打开已关闭的连接,但不能重新打开已处置的连接。 Dispose() 所做的主要额外工作是将内部设置为 null,这不会产生太大影响,因为无论如何连接都会超出范围。

关于c# - .Net : Does my connection get closed via Dispose in this example?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8620188/

相关文章:

c# - 创建具有常量唯一 ID 的可编写脚本的对象

c# - 将带有参数的命令附加到 KeyUp 事件

c# - 插入、选择和更新日期时间

c# - 将 WHERE 子句与 csv 文件一起使用 ADO.NET/C#

c# - 证书加密

c# - 验证访问 token 时出错 : The session is invalid because the user logged out

mysql - 未编译 DataColumn 中的乘积表达式,显示错误为 "Cannot find column [max]."

VB.NET 从 DataTable 对象追加表到数据库

.net - 与 MySQL 的 ODBC 连接不会添加值

c# - ORA-06550 调用 Oracle 存储过程时参数数量或类型错误