Reader.Read()即使有行也无法读取行 [英] Reader.Read() fails to read rows even though it has rows

查看:419
本文介绍了Reader.Read()即使有行也无法读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,似乎读者表明它具有返回的SQL中的行,但读者的while循环永远不会运行.我将一个消息框放在reader.hasrows作为验证,并将消息框放在while循环之后的第一行. hasrows的消息框已执行,但Read的消息框未执行.非常令人困惑.我尝试对数据库查询,它确实会返回行.这是代码段.

I have a problem where it appears that the reader indicates that it has rows from the returned SQL but the while loop for the reader never runs. I put a messagebox in the reader.hasrows as a verification and I put a messagebox on the first line after the while loop as well. The messagebox for the hasrows is executed but the messagebox for the Read is not executed. It is very puzzling. I tried the query against the database and it indeed does return rows. Here is the code snippet.

using (DbConnection connection = CADBase.DbProviderFactory.CreateConnection())
    {
        connection.ConnectionString = CADBase.DbConnectionString;
        connection.Open();

        using (DbCommand command = connection.CreateCommand())
        {
            SQL = <statement here>;
            command.CommandText = SQL

            using (DbDataReader reader = command.ExecuteReader())
            {
                    while (reader.Read())
                    {
            //NEVER MAKES IT HERE
                    } 
    }
        }
    }

推荐答案

致此问题的未来读者:请注意,发生此问题的原因是OP在查询中返回了太多列.请参阅此答案下方的评论.

To future readers of this question: note that the problem occurred because the OP was returning too many columns in the query. See the comments below this answer.

我不太确定为什么会这样,但是您实际上只需要检查一次而不是两次,并且Read()方法已经做到了.

I'm not quite sure why this is happening, but you really only need to check for rows once, not twice, and the Read() method already does this.

所以您真正需要的只是

while (reader.Read())
{
    // Do your thing
} 

这篇关于Reader.Read()即使有行也无法读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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