Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Trying to see if it is beneficial to add an if (dr.HasRows) before the while (dr.read()) function. I mean, technically if it doesn't have rows it isn't going to read, so would it matter if you checked this first?

using (SqlDataReader dr = cmd.ExecuteReader())
{
    if (dr.HasRows)
    {
        while (dr.Read())
        {
            ....do stuff here
        }
    }
}

or is this going to essentially do the exact same thing if you're just making sure it has values to provide...

using (SqlDataReader dr = cmd.ExecuteReader())
{
    while (dr.Read())
    {
        ....do stuff here
    }
}    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
472 views
Welcome To Ask or Share your Answers For Others

1 Answer

No..It is not mandatory to check (dr.HasRows) if the DataReader contains any row or not.

Read() will return False if there are no more rows to fetch, but Reader.HasRows is much more telling as to what it does than Read() so it would be a good practice to use Reader.HasRows because you may accidentally do something other than Read() which may fall into exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...