As you did not give more information I will put something that would work an application of mine. Of course you will have to make several adaptations, use the method properly or change it to take care of exceptional situations or do something other than return null if nothing is found (although in my system I would do different).
public Cliente ObterPorId(int id)
using (connection) { //imagino que esta informação está disponível na classe
using (var command = new SqlCommand("SELECT campo1, campo2 FROM Clientes WHERE Id = @id;", connection))
using (var reader = command.ExecuteReader()) {
cmd.Parameters.Add(new SqlParameter("@id", id));
connection.Open();
Cliente cliente;
if (reader.Read()) {
cliente = new Cliente();
cliente.campo1 = reader.GetString(0) //primeira coluna
cliente.campo2 = reader.GetString(1) //segunda coluna
}
}
return cliente;
}
I put in the Github for future reference.
The @id
is a parameter of query, he will be replaced by id
passed to this method as per SqlParameter
next used.
Obviously I haven’t tested it, but the general idea is this. I stress what specific needs will make the algorithm different from this. Actually this form is very simplified for some real situations. So the questions should have details.
Of course there are several other ways to get the same result.
I believe that’s right, that @id, he’s getting the id stated in the method?
– War Lock
That’s right, you pass to the query through a declared parameter.
– Maniero
and in the add Parameters, that line ("id", id)); the quote id is what?
– War Lock
https://msdn.microsoft.com/en-us/library/0881fz2y(v=vs.110). aspx is the parameter of query that you are adding. He needs to know where he will fit the
id
passed by the method within the query. I edited p/ get more obvious.– Maniero