Should I be using SqlDataReader inside a “using” statement?

前端 未结 3 1627
醉酒成梦
醉酒成梦 2020-12-29 03:02

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

In the MSDN I found this:

private static void ReadOrderDat         


        
相关标签:
3条回答
  • 2020-12-29 03:08

    Would it not be simpler to use this code?

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

    This should dispose of the reader, and the implicit connection and command when the using is terminated.

    Or have I missed something?

    0 讨论(0)
  • 2020-12-29 03:14

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

    See MSDN for more info.

    0 讨论(0)
  • 2020-12-29 03:21

    You can actually list usings together, a 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]));
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题