Datareader opens and gives error by not closing

Asked

Viewed 1,356 times

0

I have a DataReader on my website to read the data that the bank brings. There when two people enter different computers, and even different browsers, opens a connection, but at the time I will read some data VS returns me an error

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

Would you have something that could change so that several people could 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();
        }
    }
  • you are using a static Sqlconnection inside your Dados?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

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;
}

I put in the Github for future reference.

Read other questions to better understand how using and the right way to manage resources "that need to be closed":

If you still don’t understand I suggest asking more specific questions on the subject, reading a good book that teaches how to do it properly or looking for a good course that teaches you how to manage resources without risking keeping them open.

  • I was told that Static is doing this. Then when I shoot Static from my connection string, my Sqlconnection gives error. Would this Static perhaps?

  • This would be my public class Data connection string {&#xA;private static string stringConexao = @"Data Source=BF-SERVER\SQLEXPRESS,49258;Initial Catalog=SUPERBF;User ID=sa;Password=bf@12345;";&#xA;private static SqlConnection conexaoDecup = new SqlConnection(stringConexao);&#xA;public SqlConnection fechaConexao()&#xA;{&#xA;if (conexaoDecup.State == ConnectionState.Open)&#xA;{&#xA;conexaoDecup.Close();&#xA;}&#xA;return conexaoDecup;&#xA;}&#xA;public SqlConnection abreConexao()&#xA;{&#xA;if (conexaoDecup.State == ConnectionState.Closed)&#xA;{&#xA;conexaoDecup.Open();&#xA;}&#xA;return conexaoDecup; } #endregion }

  • It is possible that this is a problem as well, but not necessarily. Then we enter into a much larger context than is in the question. And it may be that the entire application is wrong. Other than it gives error because it has to change several other things to work. This comment code has the same problem I mentioned in the answer. My answer is still valid, with or without static. You need to understand several concepts to do right.

0

Good afternoon. After a long time, now I remembered to come here to show you the solution. Before I was creating a variable by pulling my connection string. And then I inserted it into Sqlconnection. To solve this problem of mine, I just put this my direct connection string into Sqlconnection. Thus remaining:

//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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.