2011-11-12 53 views
2

我正尝试从我的C#项目中使用MySQL驱动程序读取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 [email protected]"; 

     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 (reader.HasRows && reader.Read()) { 
    val = reader.GetInt32 (0); 
} 

而且现在的O/P为-1。 (数据在表格中。)如果由于某种原因结果集的行数为零,读者不应该首先进入if块。我的意思是,Read()方法的全部重点是首先检查结果集中是否有任何行。

在我的智慧结束在这里...只是不知道我要去哪里错了。

谢谢你的帮助! :)

+0

@harpo:你应该让这个评论的答案 – BrokenGlass

+0

@BrokenGlass,好吧,只是使用礼仪的头顶我的头:) – harpo

+0

在不同的情况下相同的错误http:// stackoverflow。 com/questions/6775136 /当无法尝试读取电子阅读器时关闭阅读器错误的冗长操作 – Lijo

回答

3

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

+0

有时候,解决方案就坐在你的鼻子下面,你需要有人推动你: )我只是摆脱了行:DataTable dt = new DataTable(); dt.Load(读者);有效。对于我的生活,我无法弄清楚我是如何错过的!再次感谢@harpo! – Najeeb

相关问题