Changing a row safely
An update changes an existing row. The pattern is the same as a parameterised read, with an important extra check.
The command
C#
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(
"UPDATE Product SET Name = @name WHERE Id = @id", conn))
{
cmd.Parameters.AddWithValue("@name", txtName.Text.Trim());
cmd.Parameters.AddWithValue("@id", productId);
conn.Open();
int changed = cmd.ExecuteNonQuery();
statusLabel.Text = changed + " row updated";
}Why check the count
The execute method returns how many rows changed. If the answer is zero, the record was not found. If it is more than one, your condition matched too much. Either way, you want to know.
Always name the key. An update without a precise condition changes every row in the table. The identifier in the where clause is what keeps the change narrow.
Creating a row is the mirror of this, covered in adding a new row.