Error “There is already an open DataReader associated with this Command which must be closed first” when using 2 distinct commands

后端 未结 7 1724
春和景丽
春和景丽 2020-11-29 01:23

I have this legacy code :

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

 public List

        
7条回答
  •  爱一瞬间的悲伤
    2020-11-29 01:46

    Try to combine the query, it will run much faster than executing an additional query per row. Ik don't like the string[] you're using, i would create a class for holding the information.

        public List get_dados_historico_verificacao_email_WEB(string email)
        {
            List historicos = new List();
    
            using (SqlConnection conexao = new SqlConnection("ConnectionString"))
            {
                string sql =
                    @"SELECT    *, 
                                (   SELECT      COUNT(e.cd_historico_verificacao_email) 
                                    FROM        emails_lidos e 
                                    WHERE       e.cd_historico_verificacao_email = a.nm_email ) QT
                      FROM      historico_verificacao_email a
                      WHERE     nm_email = @email
                      ORDER BY  dt_verificacao_email DESC, 
                                hr_verificacao_email DESC";
    
                using (SqlCommand com = new SqlCommand(sql, conexao))
                {
                    com.Parameters.Add("email", SqlDbType.VarChar).Value = email;
    
                    SqlDataReader dr = com.ExecuteReader();
    
                    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);
                        //System.Windows.Forms.MessageBox.Show(dados_historico[1]);
                        dados_historico[2] = dr["hr_verificacao_email"].ToString();
                        dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
                        dados_historico[4] = dr["QT"].ToString();
                        dados_historico[5] = dr["cd_login_usuario"].ToString();
    
                        historicos.Add(dados_historico);
                    }
                }
            }
            return historicos;
        }
    

    Untested, but maybee gives some idea.

提交回复
热议问题