【问题标题】:Getting exception: Invalid attempt to read when reader is closed获取异常:关闭阅读器时尝试读取无效
【发布时间】:2011-11-12 04:39:04
【问题描述】:

我正在尝试使用 MySQL 站点外的 .net 的 MySQL 驱动程序从我的 C# 项目中读取 MySQL 数据库。

虽然我对此进行了一些研究(包括this),但我仍然对为什么会发生这种情况感到困惑。我后来跑了一个尖峰,我仍然得到同样的错误。 (在运行它之前,我用一些默认值填充了数据库。)这是全部的尖峰代码。

class Program {
    static void Main (string[] args) {
        Console.WriteLine (GetUserAge ("john")); // o/p's -1
    }

    static int GetUserAge (string username) {
        string sql = "select age from users where name=@username";

        int val = -1;
        try {
            using (MySqlConnection cnn = GetConnectionForReading ()) {
                cnn.Open ();
                MySqlCommand myCommand = new MySqlCommand (sql, cnn);
                myCommand.Parameters.AddWithValue ("@username", username);

                using (MySqlDataReader reader = myCommand.ExecuteReader ()) {
                    DataTable dt = new DataTable ();
                    dt.Load (reader);

                    if (reader.Read ()) {
                        val = reader.GetInt32 (0);
                    }
                }
            }
        } catch (Exception ex) {
            Console.WriteLine (ex.Message);
        } finally {
        }

        return val;
    }

    private static MySqlConnection GetConnectionForReading () {
        string conStr = "Data Source=localhost;Database=MyTestDB;User ID=testuser;Password=password";
        return new MySqlConnection (conStr);
    }
}

上面的代码给了我一个例外:“当阅读器关闭时尝试读取无效。”

后来我像这样修改了 if 条件:

if (reader.HasRows && reader.Read ()) {
    val = reader.GetInt32 (0);
}

现在 o/p 为 -1。 (数据在表中。)如果由于某种原因结果集有零行,那么阅读器首先不应该进入 if 块。我的意思是,Read() 方法的重点是首先检查结果集中是否有任何行。

在我的智慧尽头......只是不知道我哪里错了。

感谢您的帮助! :)

【问题讨论】:

标签: c# mysql database-connection sqldatareader


【解决方案1】:

我认为使用DataTable.Load 将“消耗”读者,并且至少将其放在最后。它甚至可以解释关闭的连接(但我只是在这里猜测)。如果你删除那条线怎么办?我认为这里没有任何意义。

【讨论】:

  • 有时解决方案就在你的眼皮底下,你需要有人轻推你:) 我只是去掉了这些行: DataTable dt = new DataTable (); dt.Load(阅读器);有效。对于我的生活,我无法弄清楚我是如何错过的!再次感谢@harpo!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
相关资源
最近更新 更多