我应该在“使用"中使用 SqlDataReader 吗?陈述? [英] Should I be using SqlDataReader inside a "using" statement?

查看:29
本文介绍了我应该在“使用"中使用 SqlDataReader 吗?陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个例子哪个是正确的?(或者哪个更好,我应该使用哪个)

Which of the following two examples are correct? (Or which one is better and should I use)

在 MSDN 中我发现了这个:

In the MSDN I found this:

private static void ReadOrderData(string connectionString)
{
   string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"

   using (SqlConnection connection = new SqlConnection(connectionString))
   {
       SqlCommand command = new SqlCommand(queryString, connection);
       connection.Open();

       SqlDataReader reader = command.ExecuteReader();

       // Call Read before accessing data.
       while (reader.Read())
       {
           Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
       }

       // Call Close when done reading.
       reader.Close();
   }
}

但是,一些用户建议以这种方式查看其他页面:

However looking other pages some users suggest to do it this way:

private static void ReadOrderData(string connectionString)
{
   string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";

   using (SqlConnection connection = new SqlConnection(connectionString))
   {
       using (SqlCommand command = new SqlCommand(queryString, connection))
       {
          connection.Open();

          using (SqlDataReader reader = command.ExecuteReader())
          {
              // Call Read before accessing data.
              while (reader.Read())
              {
                    Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
              }
          }
       }
   }
}

所以,问题是:我是否应该在 SqlCommandSqlDataReader 中也使用 using 语句,或者它们会自动处理SqlConnection using 代码块的结尾.

So, the question is: should I use the using statement also in the SqlCommand and in the SqlDataReader or they are automatically disposed at the end of the SqlConnection using code block.

推荐答案

第二个选项意味着你的reader在创建后如果出现异常会关闭,所以首选.

The second option means your reader will be closed in the event of an exception after it has been created, so it is preferred.

它被编译器有效地转换为:

It is effectively transformed by the compiler to:

SqlDataReader reader = command.ExecuteReader();
try
{
    ....
}
finally
{
  if (reader != null)
      ((IDisposable)reader).Dispose();
}

有关详细信息,请参阅 MSDN.

See MSDN for more info.

这篇关于我应该在“使用"中使用 SqlDataReader 吗?陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆