我应该使用SqlDataReader的一个&QUOT内

我应该使用SqlDataReader的一个&QUOT内

本文介绍了我应该使用SqlDataReader的一个&QUOT内;使用"声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]));
              }
          }
       }
   }
}

所以,问题是:我应该使用使用语句也可以在的SqlCommand SqlDataReader的或会被自动设置在年底的的SqlConnection 使用 code座。

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.

推荐答案

第二个选项意味着将在出现异常的情况下,它已被创建之后关闭,所以它是preferred

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的一个&QUOT内;使用"声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:13