问题
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
}
}
}
}
回答1:
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.
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.
So all you really need is
while (reader.Read())
{
// Do your thing
}
回答2:
call MoveNext() before first call to read
回答3:
You should use reader.HasRows property and not the method.
回答4:
Maybe you're getting an exception on reader.Read()
.
But since HasRows is a property and not a method. You need to write if(reader.HasRows)
to make it compile.
if(reader.HasRows)
{
//MAKES IT HERE
while (reader.Read())
{
//NEVER MAKES IT HERE
}
}
So i'm wondering what the actual code is.
回答5:
Just a guess. Maybe you are accessing the reader object in that messagebox shown after reader.HasRows and before reader.Read(). Apparently the Read() method returns true only if the reader has NOT reached the last row (see: https://stackoverflow.com/a/1540626/516481). So if the reader is at the last row it will return false! Maybe the query returns just one row and you change the internal state of the reader object somehow by accessing it (maybe using the debugger) and moving the reader to the last row?
来源:https://stackoverflow.com/questions/13843267/reader-read-fails-to-read-rows-even-though-it-has-rows