Many tutorials I've seen compose SQL statements by using variables and Parameters.Add
, like 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)
instead?
Parameterized SQL queries allow you to place parameters in an SQL query instead of a constant value. A parameter takes a value only when the query is executed, which allows the query to be reused with different values and for different purposes.
Simply using String. Format does not protect against SQL injection attacks.
public IEnumerable<SampleModel> RetrieveSampleByFilter(string query, params SqlParameter[] parameters) { using(var connection = new SqlConnection(dbConnection)) using(var command = new SqlCommand(query, connection)) { connection. Open(); if(parameters. Length > 0) foreach(var parameter in parameters) command.
AddWithValue replaces the SqlParameterCollection. Add method that takes a String and an Object. The overload of Add that takes a string and an object was deprecated because of possible ambiguity with the SqlParameterCollection.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With