c# – Doubt about the error "Error converting data type varchar to float"


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);

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?


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;

Parameters resolve the type of the variable for you, prevent SQL Injection and strange behavior at execution. See more here .

Scroll to Top