DataReader opens and gives error for not closing

0

I have DataReader on my website to read the data the bank brings. I have a problem with VS, but I do not know how to do it.

  

There is already an open DataReader associated with this Command that must be closed first

Would there be anything that could change for several people to access at the same time? Close DataReader?

 public static List<dMovimentoUser> listar_lancamentos(string conexao)
    {
        List<dMovimentoUser> carrinho = new List<dMovimentoUser>();
        Dados objDados = new Dados();
        SqlCommand command = new SqlCommand("usp_lancamentos_internos_listar", objDados.abreConexao());
        command.Parameters.AddWithValue("@conexao", conexao);
        command.CommandType = CommandType.StoredProcedure;
        SqlDataReader reader;
        reader = command.ExecuteReader();
        objDados.abreConexao();

        try
        {

            while (reader.Read())
            {
                dMovimentoUser ct = new dMovimentoUser();
                ct.codigo = reader["código"].ToString();
                ct.descricao = reader["produto"].ToString();
                ct.data = reader["data"].ToString();
                ct.hora = reader["hora"].ToString();
                ct.operacao = reader["operacao"].ToString();
                ct.qtd = float.Parse(reader["quantidade"].ToString());
                ct.historico = reader["historico"].ToString();
                carrinho.Add(ct);
            }
            return carrinho;
        }
        catch (Exception ex)
        {
            throw new Exception("Erro encontrado: " + ex.Message);
        }
        finally
        {
            reader.Close();
            objDados.fechaConexao();
        }
    }
    
asked by anonymous 18.10.2016 / 14:24

2 answers

2

This code has some problems.

public static List<dMovimentoUser> listar_lancamentos(string conexao) {
    var carrinho = new List<dMovimentoUser>();
    varobjDados = new Dados();
    //temo que esse abreConexao deve estar causando problema também
    using (var command = new SqlCommand("usp_lancamentos_internos_listar", objDados.abreConexao()) {
        command.Parameters.AddWithValue("@conexao", conexao);
        command.CommandType = CommandType.StoredProcedure;
        using (var reader = command.ExecuteReader()) { //o using garante o fechamento
        //esse abreConexao não deve ter sido escrito do jeito correto também.
        objDados.abreConexao(); //de novo? isso está muito errado
        //já que não está fazendo nada útil com a exceção, é melhor não tratá-la aqui
        //se vai relançar a exceção sem resolver nada, não capture, principalmente Exception
        while (reader.Read()) {
            var ct = new dMovimentoUser();
            ct.codigo = reader["código"].ToString(); //acho que isso pode ser simplificado
            ct.descricao = reader["produto"].ToString();
            ct.data = reader["data"].ToString();
            ct.hora = reader["hora"].ToString();
            ct.operacao = reader["operacao"].ToString();
            ct.qtd = float.Parse(reader["quantidade"].ToString());
            ct.historico = reader["historico"].ToString();
            carrinho.Add(ct);
        }
        return carrinho;
    }
}

Read other questions to better understand how using works and the right way to manage "closed" features:

If I still do not understand I suggest asking more specific questions on the subject, read a good book that teaches you how to do it correctly or look for a good course that teaches you how to manage resources without risk of keeping them open.

    
18.10.2016 / 14:43
0

Good afternoon. After a long time, I remembered to come here to show the solution. Before I'm creating a variable by pulling my connection string. And then I inserted it into SqlConnection. To solve this problem, I just put my direct connection string in SqlConnection. Staying like this:

//O que dá erro
private static string stringConexao = @"Data Source=instacia;Initial Catalog=banco;User ID=sa;Password=******; MultipleActiveResultSets = true"
private static SqlConnection conexaoDecup = new SqlConnection(stringConexao);

//O que deu certo
private SqlConnection conexaoDecup = new SqlConnection(@"Data Source=instacia;Initial Catalog=banco;User ID=sa;Password=******; MultipleActiveResultSets = true");

That's it. Thank you to those who tried to help me.

    
02.12.2016 / 20:13