Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top