0

我在从 MySQL 数据库读取记录时面临 ASP.NET c# 中的 DataReader 打开连接问题。我不知道第一次执行 datareader 时它如何显示我打开的连接。

DAL 的错误如下

MySqlDataReader reader = myCommand.ExecuteReader();

已经有一个打开的 DataReader 与此 Connection 关联,必须先关闭它

示例代码

// BAL function call the DAL function 

MainFunction()
{
...
...
  using (MySqlDataReader reader = clsDAL.GetALL(SqlQuery, Parms))
            {
                while (reader.Read())
                {
                    clsVitalsDisplay obj = new clsVitalsDisplay();

                    obj.BySessionId = Convert.ToInt32(reader["BySessionId"].ToString());
                    obj.ByDevSessionId_LifeTouchHeartRate = Convert.ToInt32(reader["ByDevSessionId_LifeTouchHeartRate"].ToString());
                    obj.HumanReadableDeviceId_LifeTouch = reader["HumanReadableDeviceId_LifeTouch"].ToString();

                    listLifetouchHeartRate.Add(obj);
                }
            }
}

// Getting the Error while Read the details from database in DAL (Data Access Layer) class at MySqlDataReader reader = myCommand.ExecuteReader();

 public static MySqlDataReader GetALL(String _query, MySqlParameter[] sqlParameter)
    {
        MySqlCommand myCommand = new MySqlCommand();

        try
        {
            myCommand.Connection = OpenConnection();
            myCommand.CommandText = _query;
            myCommand.Parameters.AddRange(sqlParameter);
            myAdapter.SelectCommand = myCommand;
//Face the error at below line
            MySqlDataReader reader = myCommand.ExecuteReader();
            myCommand.Dispose();
            return reader;
        }
        catch (MySqlException ex)
        {
            ErrorLog.ErrorLog.Log_Err("", ex, Global.gUserId.ToString());
            return null;
        }
        finally
        {

        }
    }
4

1 回答 1

0

我已经通过关闭已经打开的数据库连接来解决这个问题,如果打开如下。之后它工作正常。

public static MySqlDataReader GetALL(String _query, MySqlParameter[] sqlParameter)
    {
        MySqlCommand myCommand = new MySqlCommand();

        try
        {
             if (con.State == ConnectionState.Open)
                {
                con.Close();
                }

            myCommand.Connection = OpenConnection();
            myCommand.CommandText = _query;
            myCommand.Parameters.AddRange(sqlParameter);
            myAdapter.SelectCommand = myCommand;

            MySqlDataReader reader = myCommand.ExecuteReader();
            myCommand.Dispose();
            return reader;
        }
        catch (MySqlException ex)
        {
            ErrorLog.ErrorLog.Log_Err("", ex, Global.gUserId.ToString());
            return null;
        }
        finally
        {

        }
    }
于 2015-06-23T09:07:47.060 回答