Problem with sql query in my ASP.NET core application

Asked

Viewed 134 times

-2

I’m having trouble at the time I need to query information in the database through my sql command in my Asp.Net Core application. I’ve done research here at Stackoverflow and I can’t find.

Error: System.Data.SqlClient.SqlException: 'É necessário declarar a variável escalar "@ClienteId".'

Method responsible for carrying out this consultation:

 public Cliente ConsultarCliente(long? id)
    {

        Cliente item;
        DAL acessarBanco = new DAL(); // Instanciando objeto acessar banco para realizar a conexão de dados.
        string sqlConsulta = string.Format("SELECT * FROM Estudo.Clientes WHERE ClienteId = @ClienteId");

        //string sqlConsulta = $"Select ClienteId, Nome, CpfCnpj, Email, Senha From Estudo.Clientes Where ClienteId ='{ClienteId}' order by Nome asc"; //  variavel sqlConsulta para trazer todas os registros da tabela Clientes.
        DataTable dt = acessarBanco.RetDataTable(sqlConsulta);



        item = new Cliente
        {
            ClienteId = dt.Rows[0]["ClienteId"].ToString(),
            Nome = dt.Rows[0]["Nome"].ToString(),
            CpfCnpj = dt.Rows[0]["CpfCnpj"].ToString(),
            Email = dt.Rows[0]["Email"].ToString(),
            Senha = dt.Rows[0]["Senha"].ToString()
        };

        return item;
    }

DAL class with my connection:

 public DAL()

    {
        Conexao = new SqlConnection(StringConexao);
        Conexao.Open();
    }

    public DataTable RetDataTable(string sql)
    {
        DataTable data = new DataTable();
        SqlCommand Executar = new SqlCommand(sql, Conexao);
        SqlDataAdapter da = new SqlDataAdapter(Executar);
        da.Fill(data);
        return data;
    }

1 answer

1


In the query the variable @Clienteid is being indicated but this is not being filled in. Usually when a variable is used, it is filled with a value to dynamically apply a filter.
Ex: replace the text "@Clienteid" by the code of a client or ID.

What is the purpose of the Where filter in the SQL query?

  • Antonio, good night to you. I’m trying to call a record by the id parameter, by identifying the id 5 for example it brings me with the fields filled in so I can perform this change..

  • worked out here thanks.

Browser other questions tagged

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