I saw in many tutorial that compose sql statement by using variable and Parameters.Add likt this
public void updateStudent(String @studentID, String @firstName, String @lastName)
{
SQLiteCommand command = conn.CreateCommand();
command.CommandText = "UPDATE Students SET firstName = @firstName, lastName = @lastName WHERE studentID = @studentID";
command.Parameters.Add(new SQLiteParameter("@studentID", @studentID));
command.Parameters.Add(new SQLiteParameter("@firstName", @firstName));
command.Parameters.Add(new SQLiteParameter("@lastName" , @lastName));
command.ExecuteNonQuery();
}
why don't we use
string.Format("Update Students SET firstName = '{0}', lastName = '{1}...", @firstName, @lastname)
any benefit??
Four reasons:
Also note:
You don't need to use @
as a prefix to your variables unless they're keywords. So it would be more idiomatic to write:
command.Parameters.Add(new SQLiteParameter("@lastName", lastName));
(Ditto for the method parameter declarations to start with... but not the parameters inside the SQL statement.)
See more on this question at Stackoverflow