c# - 我们需要使用 SqlCommand 还是仅用于 SqlConnection 和 SqlDataReader

标签 c# ado.net

我从 msdn 中获取了这段代码

string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";

    using (SqlConnection conn = new SqlConnection(connString))
    {
      SqlCommand cmd = conn.CreateCommand();
      cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";

      conn.Open();

      using (SqlDataReader dr = cmd.ExecuteReader())
      {
        while (dr.Read())
          Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
      }
    }

如您所见,这里没有使用 SqlCommand,那么,它需要吗?

最佳答案

您创建的每个实现IDisposable 的对象都需要一个using。这包括 SqlCommandSqlConnection


这条规则几乎没有异常(exception)。主要的异常(exception)是 WCF 客户端代理。由于设计缺陷,他们的 Dispose 方法有时会抛出异常。如果您在 using 语句中使用代理,则第二个异常会导致您丢失原始异常。

关于c# - 我们需要使用 SqlCommand 还是仅用于 SqlConnection 和 SqlDataReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2252062/

相关文章:

c# - Entity Framework VS 纯 Ado.Net

C# 数据库中的多个并行插入

ado.net - 在 ADO.NET 中向 SQL Server 表添加行而不需要硬编码 SQL 的最直接方法是什么?

c# - SCOPE_INDENTITY() 不工作它返回 null 吗?

C# Excel Interop - 调用 Worksheet.ExportAsFixedFormat 时抑制 'Publishing' 对话框

c# - 在 C# 中设置风扇速度

c# - 在 ASP.Net 中动态取消选中复选框时,CheckBox 不会触发 CheckedChanged 事件

c# - 将 json 中的图像的 base64 字节数组传递给 webApi

c# - 读取 Dictionary<string, object> 中的值

c# - ASP.Net C# - 根据条件设置 MySQL 查询和参数