Reading rows with a parameterised query
When a query depends on a value the visitor supplied, that value must travel as a parameter, never as part of the query text.
The parameter pattern
C#
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(
"SELECT Id, Name FROM Product WHERE Category = @cat", conn))
{
cmd.Parameters.AddWithValue("@cat", ddlCategory.SelectedValue);
var table = new DataTable();
conn.Open();
new SqlDataAdapter(cmd).Fill(table);
resultsGrid.DataSource = table;
resultsGrid.DataBind();
}Why this matters
- The value is treated as data, not as part of the command, which closes the door on injection.
- The type is handled for you, so a date or a number arrives intact.
- The same command can run many times with different values.
One habit worth keeping for life. If you ever find yourself gluing text into a query, stop and use a parameter instead. It is almost always less code anyway.
The same pattern writes data, beginning with adding a new row.