C# has a handy statement that closes and releases resources automatically: the using
command. It does so, even if the using
block is left prematurely because of an error or because of a return
or break
statement. You were closing the connection twice. In my example below, I use the using
-statement in order to close the connection, the command and the reader.
You should not keep the connection open. This potentially consumes resources over a long time. Open it and close it (with using
) each time you need a connection. The connection pool automatically keeps connections open for some time, so that the "physical" connection will not be constantly closed and reopened.
Before a record can be accessed you must move to the first (or next) record with dr.Read()
. This method also returns a Boolean value telling you whether a record was there and whether the operation could be performed. Use dr.Read()
instead of dr.HasRows
.
I am also using a command parameter, which is both easier and safer as stitching the command together with string operations.
public Veiculo getVehiclebyMatricula(string MAT)
{
Veiculo V = new Veiculo();
query = "select * from Veiculo where matricula = @m";
using (SqlConnection conn = CNManager.getConnection())
using (var command = new SqlCommand(query, conn)) {
command.Parameters.AddWithValue("@m", MAT);
conn.Open();
using (SqlDataReader dr = command.ExecuteReader()) {
if (dr.Read()) {
V._id = Convert.ToInt32(dr["_id"]);
V.marca = dr["marca"].ToString();
V.modelo = dr["modelo"].ToString();
V.matricula = dr["matricula"].ToString();
V.estado = Convert.ToChar(dr["estado"]);
V.preco = Convert.ToInt32(dr["preco"]);
V.cilindrada = Convert.ToInt32(dr["cilindrada"]);
V.image = dr["_src"].ToString();
V.id_tipo = Convert.ToInt32(dr["id_tipo"]);
}
}
}
return V;
}