已经有一个与此连接关联的打开的 DataReader,必须先关闭该读取器
本文关键字:读取 有一个 连接 关联 DataReader | 更新日期: 2023-09-27 17:56:39
我在从MySQL数据库读取记录时 ASP.NET c#中面临DataReader打开连接问题。我不知道如何在第一次执行数据读取器时向我显示打开的连接。
DAL的错误如下
MySqlDataReader reader = myCommand.ExecuteReader();
已经有一个与此连接关联的打开的数据读取器,必须先关闭
示例代码
// 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
{
}
}
我已经通过关闭已经打开的数据库连接(如果打开如下)来解决此问题。之后它工作正常。
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
{
}
}