3

I have some strange problem. I use MySQL Connector.NET but MySqlReader.Read() sometimes returns true and sometimes false. MySqlReader.HasRows is true both cases and in VisualStudio I can see that reader object hold all values.

Why could that happen?

Here is my code:

MySqlCommand sqlCommand = new MySqlCommand(sqlCode, this._conn);
MySqlDataReader rdr = sqlCommand.ExecuteReader();
PopulateMessage("--> " + serverName + ": " + dbName);
int fields = rdr.VisibleFieldCount;

//make headers
int[] fmaxl = new int[fields];
string[] headers = new string[fields];
List<string[]> vals = new List<string[]>();
if (rdr.HasRows)
{
        for (int hi = 0; hi < fields; hi++)
        {
                string val = rdr.GetName(hi);
                headers[hi] += val;
                fmaxl[hi] = val.Length;
        }
        while (rdr.HasRows && rdr.Read()) // <-- here the Read() method returns 
                                          //     false or true sometimes
                                          //     while HasRows is true
        {
                ...

EIDT: The rdr holds for example 99 rows with values (checked in VS) and at first call the Read() method returns false. Thanks Joachim for making me put this useful notice.

3
  • which version of connector are you using? and which MySQL? Commented Jul 15, 2013 at 12:15
  • I feel like the code inside the while is relevant. Commented Jul 15, 2013 at 12:18
  • @MichaelPerrenoud - how can it be relevant if Read() returning false prevents entering "into the while" ;) Commented Jul 15, 2013 at 12:25

1 Answer 1

1

This HasRows property isn't in all versions of .net. Why not recast your code like this?

boolean firstRow = true;
while (rdr.Read()) 
{
   if (firstRow) {   // get the column names, but only once 
       firstRow = false;
       for (int hi = 0; hi < fields; hi++)
       {
            string val = rdr.GetName(hi);
            headers[hi] += val;
            fmaxl[hi] = val.Length;
       }
    }

    ... //process each row.
}

Having done tonnage of this kind of stuff, I know this works pretty well.

Sign up to request clarification or add additional context in comments.

2 Comments

I find it odd as it is pretty much the same I do but it is acutally working. Thank you Ollie!
Yah, side-effect method and property calls sometimes do strange things, especially deprecated ones like HasRows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.