数据库
首页 > 数据库> > 当使用MySql数据库时,第二次查询时报错“There is already an open DataReader associated with this Connection which must

当使用MySql数据库时,第二次查询时报错“There is already an open DataReader associated with this Connection which must

作者:互联网

1,由于MySqlConnection(数据库连接)的对象是全局变量引用,虽然可以通过关闭数据库连接清除报警,但占用资源较大。--未采用

1  MySqlConnection sqlConnection = new MySqlConnection(connectionstr);
2 sqlConnection.Open();
3 //ToDo:
4 sqlConnection.Close();
5 sqlConnection.Dispose();

2,通过查找资料,发现可以通过using关键字自动释放。--一般这种情况都可以解决

using (MySqlCommand sqlCommand = new MySqlCommand(insertQuery, sqlConnection))
                    {
                        sqlCommand.CommandType = CommandType.Text;
                        foreach (MySqlParameter pa in parameters)
                        {
                            sqlCommand.Parameters.Add(pa);
                        }
                        rows = sqlCommand.ExecuteNonQuery();
                    }         

3,当对再次数据库进行查询时,还是出现之前问题。

 1  using (MySqlCommand sqlCommand = new MySqlCommand(queryStr, sqlConnection))
 2  {
 3      sqlCommand.CommandType = CommandType.Text;
 4      MySqlDataReader reader = sqlCommand.ExecuteReader();
 5       while (reader.Read())
 6              {
 7                  DataRow dr = dataTable.NewRow();
 8                  int count = reader.FieldCount;
 9                  for (int i = 0; i < count; i++)
10                      {
11                         dr[i] = reader.GetString(i);
12                       }
13                      dataTable.Rows.Add(dr);
14              }
15  }    
View Code

通过排查发现,MySqlDataReader reader 导致的,做法如下

①每次使用前 MySqlDataReader reader=null;

②在finally块中,对reader进行释放。 reader?.Close(); reader?.Dispose();

标签:MySqlCommand,DataReader,associated,There,new,CommandType,reader,sqlConnection,sq
来源: https://www.cnblogs.com/weber-zheng/p/16424425.html