Reader.Read()即使有行也无法读取行

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
}