草庐IT

c# - 使用 2 个不同的命令时出现错误 "There is already an open DataReader associated with this Command which must be closed first"

coder 2023-07-08 原文

我有这个遗留代码:

 private void conecta()
 {  
     if (conexao.State == ConnectionState.Closed)
         conexao.Open();
 }

 public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
 {
     List<string[]> historicos = new List<string[]>();
     conecta();

     sql = 
         @"SELECT * 
         FROM historico_verificacao_email 
         WHERE nm_email = '" + email + @"' 
         ORDER BY dt_verificacao_email DESC, hr_verificacao_email DESC";

     com = new SqlCommand(sql, conexao);
     SqlDataReader dr = com.ExecuteReader();

     if (dr.HasRows)
     {
         while (dr.Read())
         {
             string[] dados_historico = new string[6];
             dados_historico[0] = dr["nm_email"].ToString();
             dados_historico[1] = dr["dt_verificacao_email"].ToString();
             dados_historico[1] = dados_historico[1].Substring(0, 10);
             dados_historico[2] = dr["hr_verificacao_email"].ToString();
             dados_historico[3] = dr["ds_tipo_verificacao"].ToString();

             sql = 
                 @"SELECT COUNT(e.cd_historico_verificacao_email) QT 
                 FROM emails_lidos e 
                 WHERE e.cd_historico_verificacao_email = 
                     '" + dr["cd_historico_verificacao_email"].ToString() + "'";

             tipo_sql = "seleção";
             conecta();
             com2 = new SqlCommand(sql, conexao);

             SqlDataReader dr3 = com2.ExecuteReader();
             while (dr3.Read())
             {
                 //quantidade de emails lidos naquela verificação
                 dados_historico[4] = dr3["QT"].ToString(); 
             }
             dr3.Close();
             conexao.Close();

             //login
             dados_historico[5] = dr["cd_login_usuario"].ToString();
             historicos.Add(dados_historico);
         }
         dr.Close();
     }
     else
     { 
         dr.Close();
     }

     conexao.Close();
     return historicos;
 }


我已经创建了两个单独的命令来纠正这个问题,但它仍然继续:“已经有一个与此命令关联的打开的 DataReader,必须先将其关闭”。

附加信息:相同的代码在另一个应用程序中运行。

最佳答案

只需在您的连接字符串中添加以下内容:

MultipleActiveResultSets=True;

关于c# - 使用 2 个不同的命令时出现错误 "There is already an open DataReader associated with this Command which must be closed first",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18475195/

有关c# - 使用 2 个不同的命令时出现错误 "There is already an open DataReader associated with this Command which must be closed first"的更多相关文章

随机推荐