本文介绍了如果我调用 SqlReader.Read,我应该调用 SqlDataReader.HasRows的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试看看在while (dr.read()) 函数之前添加一个if (dr.HasRows) 是否有益.我的意思是,从技术上讲,如果它没有行,它就不会读取,所以如果你先检查这个会有关系吗?

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
    }
}

推荐答案

没有.如果 DataReader 包含任何行,检查 (dr.HasRows) 不是强制性的.

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

Read() 将返回 False 如果没有更多的行要获取,但 Reader.HasRows 更能说明什么它比 Read() 更有效,因此使用 Reader.HasRows 将是一个好的做法,因为您可能会不小心做一些除了 Read() 可能会陷入异常的事情.

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.

这篇关于如果我调用 SqlReader.Read,我应该调用 SqlDataReader.HasRows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:08