如果我正在调用SqlReader.Read,我应该调用SqlDataReader.HasRows吗? [英] Should I call SqlDataReader.HasRows if I am calling SqlReader.Read

查看:146
本文介绍了如果我正在调用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
    }
}    

推荐答案

否.不必强制检查(dr.HasRows) DataReader是否包含任何行.

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

Read()将返回 False ,但是Reader.HasRowsRead()更具说服力,因此它将是 优良作法 以使用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吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆