Question:
Error converting data type varchar to float
This error is occurring when I perform an Update
on a table, below is the code:
SqlCommand cmd = new SqlCommand("UPDATE Notas SET nota = '" + nota.nota + "' WHERE idMateria = '" + nota.idMateria + "' and idAluno = '" + nota.idAluno + "';", con);
cmd.ExecuteNonQuery();
The note field is created in the DB as float
, I've tried to perform the conversion but I'm not getting it, any tips?
Answer:
You need to use parameters:
var cmd = new SqlCommand(@"UPDATE Notas
SET nota = @nota
WHERE idMateria = @idMateria
and idAluno = @idAluno", con);
cmd.Parameters.Add("@nota", SqlDbType.Float).Value = nota.nota;
cmd.Parameters.Add("@idMateria", SqlDbType.Int).Value = nota.idMateria;
cmd.Parameters.Add("@idAluno", SqlDbType.Int).Value = nota.idAluno;
cmd.ExecuteNonQuery();
Parameters resolve the type of the variable for you, prevent SQL Injection and strange behavior at execution. See more here .