lately, I've seen a lot of people using the Parameters property of an SQLCommand to provide simple values to the query - like this:
var one = "one";
var two = "two";
DataTable results = new DataTable();
string cmdTxt = String.Format("select NAME from TABLE where NAME like @ONE or NAME like @TWO");
using (SqlCommand cmd = new SqlCommand(cmdTxt, Butch.connection))
{
cmd.Parameters.Add("@ONE", SqlDbType.Char, 15).Value = "%" + one + "%";
cmd.Parameters.Add("@TWO", SqlDbType.Char, 65).Value = "%" + two + "%";
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
adapter.Fill(results);
}
Historically, I've just embedded the values in the query string like this:
var one = "one";
var two = "two";
DataTable results = new DataTable();
string cmdTxt = String.Format($"select NAME from TABLE where NAME like '%{one}%' or NAME like '%{two}%");
using (SqlCommand cmd = new SqlCommand(cmdTxt, Butch.connection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
adapter.Fill(results);
}
I know that there are situations where cmd.Parameters.Add()
is specifically useful (like inserting binary data), so I'm not asking about those.
I'm specifically asking:
For a simple value, what is the advantage to using cmd.Parameters.Add()
(as in the first code example) rather than embedding that value in the query string (as in the second example)?
Edit to add:
Some of the comments have referenced the fact that I declared variables one
and two
as hard-coded. I did that so that the example would be complete - naturally, the variables would come from somewhere else.