【问题标题】:MySQL .Net Connector - MySqlReader.Read() returns falseMySQL .Net 连接器 - MySqlReader.Read() 返回 false
【发布时间】:2013-07-13 06:54:01
【问题描述】:

我有一些奇怪的问题。我使用 MySQL Connector.NET,但 MySqlReader.Read() 有时返回 true,有时返回 false。 MySqlReader.HasRows 在这两种情况下都是正确的,在 VisualStudio 中我可以看到 reader 对象包含所有值。

为什么会这样?

这是我的代码:

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: rdr 包含例如 99 行的值(在 VS 中检查),第一次调用 Read() 方法返回 false。感谢 Joachim 让我发布这个有用的通知。

【问题讨论】:

  • 您使用的是哪个版本的连接器?和哪个 MySQL?
  • 我觉得while里面的代码是相关的。
  • @MichaelPerrenoud - 如果Read() 返回false 阻止输入“进入”,它怎么可能相关;)

标签: c# mysql mysql-connector mysqldatareader


【解决方案1】:

此 HasRows 属性并非在所有版本的 .net 中都存在。为什么不这样重铸你的代码呢?

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.
}

已经完成了这种东西的吨位,我知道这很有效。

【讨论】:

  • 我觉得这很奇怪,因为它几乎和我一样,但它确实有效。谢谢你奥利!
  • 是的,副作用方法和属性调用有时会做一些奇怪的事情,尤其是像 HasRows 这样已弃用的方法。
猜你喜欢
  • 1970-01-01
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多