Error query in database: here is no Row at position 0

Asked

Viewed 155 times

1

I am trying to make a query in the database when calling my method and Row error occurs at position 0.

 public Cliente ConsultarCliente(long? id)
    {

        Cliente item;
        DAL acessarBanco = new DAL(); // Instanciando objeto acessar banco para realizar a conexão de dados.
        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;
    }

[I’m a beginner in c#]

  • Does the query bring any results? If you run the query directly in SQL, it returns results?

  • 2

    should check if there is a record before fetching the data in the datatable... the first part of the code demonstrates a better way to execute the SQL command: https://answall.com/a/247993/69359

  • 1

    It also has a serious security problem.

  • @Rovannlinhalis worked here, actually was making the wrong query. string sqlConsult = string.Format($"SELECT * FROM Study.WHERE clients Clienteid = {Clienteid}");, and in my id parameter was coming id 2 for example. Ai in my query I left it like this: string sqlConsult = string.Format($"SELECT * FROM Study.Clients WHERE Clienteid = {id}"); which is the id of the parameter ai worked.

  • Are you sure that the Id should be the long and that its DAL should execute any text that is passed to you and not a SqlCommand with its defined and typed parameters? As @Maniero said, you have serious security issues in your application.

No answers

Browser other questions tagged

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