读取器关闭时无效的读取尝试

时间:2011-04-01 17:44:47

标签: c# sqldatareader

我正在处理C#和MySql请求。我正在尝试在我的数据库中检索我的数据但是我有这样的错误消息:读取器关闭时无效的读取尝试。

感谢您的帮助:)

我有这个功能:

public MySqlDataReader GetValueFromTable(string table, ArrayList attribut, ArrayList parameter)
{
   string query = string.Empty;
   MySqlDataReader rdr = null;      
   try
   {
      query = "SELECT * FROM `" + table + "` WHERE ";
      for (int i = 0; i < attribut.Count; i++)
      {
         query += attribut[i] as string;
         query += " = ";
         query += parameter[i] as string;

         if(i != attribut.Count - 1) 
            query += " AND ";
      }

      query += ";";

      using (mysqlConnection)
      {
          using (mysqlCommand = new MySqlCommand(query, mysqlConnection))
          {                  
             rdr = mysqlCommand.ExecuteReader();
          }   
      }
   }
   catch (Exception ex)
   {
      Debug.Log(ex.ToString());
   }
   finally {}

   return rdr;
}

然后在我的代码中的某个地方我这样做:

ArrayList attribut = new ArrayList();       
ArrayList parameter = new ArrayList();

attribut.Add("usern_id"); 
parameter.Add("1");     
MySqlDataReader reader = dataBase.GetValueFromTable("papillon", attribut, parameter);
reader.Read();
Debug.Log(reader[0]);
reader.Close();

3 个答案:

答案 0 :(得分:7)

使用块在此处关闭连接(在退出时)

using (mysqlCommand = new MySqlCommand(query, mysqlConnection))

答案 1 :(得分:2)

如果我没有弄错的话,那就是杀死读者的使用声明。一旦使用块终止,IDisposable将触发MySQLConnection,关闭并处理与数据库的连接。

答案 2 :(得分:1)

您的读者正在关闭,因为它包含在使用语句中。当处理命令和连接时,读者也是如此。在处理读卡器之前,您需要先取出数据。

相关问题