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.

Joe
  • 2,481
  • 6
  • 34
  • 60

1 Answers1

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.

O. Jones
  • 81,279
  • 15
  • 96
  • 133
  • I find it odd as it is pretty much the same I do but it is acutally working. Thank you Ollie! – Joe Jul 15 '13 at 12:35
  • Yah, side-effect method and property calls sometimes do strange things, especially deprecated ones like HasRows. – O. Jones Jul 15 '13 at 14:11