Alexander Song Alexander Song - 3 months ago 7
SQL Question

How to update table in SQL?

Trying to update the table Student_Course in a database in SQL, it runs but I keep getting


Violation of Primary Key, Cannot enter duplicate


I really just need to update the marks value but need to match it to the CID (Course ID) and SID(Student ID)

private void btnAdd_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
try
{
using (var cmd = new SqlCommand("UPDATE Student_Course SET CID=@CID, SID=@SID , Mark=@Mark", con))
{
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("@CID", cboCID.GetItemText(cboCID.SelectedItem));
cmd.Parameters.AddWithValue("@SID", cboSID.GetItemText(cboSID.SelectedItem));
cmd.Parameters.AddWithValue("@Mark", Convert.ToInt32(txtMark.Text));

if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Mark Added");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error during insert: " + ex.Message);
}
}
}

Answer
"UPDATE Student_Course SET Mark = @Mark WHERE CID=@CID AND SID=@SID"

This should be the correct SQL statement because you are trying to update the Mark field in your Student_Course table based on the CID & SID of the person.

Comments