我应该在“using”语句中使用SqlDataReader吗?

时间:2013-02-07 16:12:19

标签: c# .net ado.net sqlconnection

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

在MSDN中我发现了这个:

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

然而,在查看其他页面时,一些用户建议这样做:

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

所以,问题是:我是否应该在usingSqlCommand中使用SqlDataReader语句,或者它们会自动放在SqlConnection的末尾using代码块。

3 个答案:

答案 0 :(得分:33)

第二个选项意味着您的reader将在创建后发生异常时关闭,因此首选。

编译器将其有效地转换为:

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

有关详细信息,请参阅MSDN

答案 1 :(得分:15)

你实际上可以一起列出使用,la:

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

答案 2 :(得分:1)

使用此代码会不会更简单?

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

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

这应该处理读取器,以及终止使用时的隐式连接和命令。

或者我错过了什么?