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
                            }

                    }
2
  • Best is opinion based. These kind of questions are off-topic on SO. Commented Jul 25, 2016 at 14:43
  • @TimSchmelter Thanks, Just want to know if it is needed to check NULL condition with HasRow Commented Jul 25, 2016 at 14:45

1 Answer 1

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? 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.