the sandman
the sandman

Reputation: 1029

SqlConnection Not Reading

I have a SQL Command that query's a DB table and retrieves information....very basic.

I can see the reader has the results from the DB table when debugging, but for some reason it always skips on "While Reader.Read" and then skips down and closes the connection never reading the data.

    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("lbx_EmailDomains_SELECT", con);
    cmd.CommandType = CommandType.StoredProcedure;

    con.Open();
    SqlDataReader reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
        while (reader.Read())
        {
           // Never Reaches Here
        }
    }

    reader.Close();
    con.Close();

UPDATE: Removing the reader.HasRows fixed the issue.

Upvotes: 0

Views: 173

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500865

My guess is that actually it's not getting as far as reader.Read(). I suspect that reader.HasRows is returning false, precisely because you haven't called reader.Read() yet.

I don't think the test for HasRows is useful at all, to be honest - I'd just get rid of it.

Note that it would be better to use using statements and get rid of the manual Close() calls, so that the connection/reader will be closed even in the event of an exception.

EDIT: According to the comments:

  • It should work, and this pattern is shown in some MSDN documentation
  • HasRows was apparently returning true before reader.Read() returned false
  • Removing the HasRows test apparently fixed the problem. Odd.

I wonder whether there's some debugger interaction we don't know about here...

Upvotes: 4

Related Questions