0

I am reading data from DB using SqlDataReader. What is best way to check, before reading data. Which one is best out of 3

Method 1

 using (SqlDataReader objReader = sqlCommand.ExecuteReader())
                    {
                        if (objReader != null)
                        {
                            while (objReader.HasRows && objReader.Read())
                            {
                                //code
                            }
                        }
                    }

Method 2

                using (SqlDataReader objReader = sqlCommand.ExecuteReader())
                    {
                        if (objReader != null)
                        {
                            while (objReader.Read())
                            {
                                //code
                            }
                        }
                    }

Method 3

               using (SqlDataReader objReader = sqlCommand.ExecuteReader())
                    {

                            while (objReader.HasRows && objReader.Read())
                            {
                                //code
                            }

                    }
user1926138
  • 1,464
  • 7
  • 34
  • 53

1 Answers1

1

Afaik SqlCommand.ExecuteReader never returns null. It can throw various excpetions but it's never null. So this check is redundant.

You also don't need to check if it HasRows in every loop iteration. That information is useful only at the beginning and not every time. But it is not necessary. You won't get any errors if you try to read records when there are none.

So i'd prefer(opinion-based) this:

using (SqlDataReader objReader = sqlCommand.ExecuteReader())
{
    if(objReader.HasRows)
    {
        while (objReader.Read())
        {
            //code
        }
    }
    else
    {
      // output/ log this? 
    }
}
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939