从文本框更新记录时,无法将重复值插入数据表中

时间:2018-01-06 14:50:34

标签: c#

尝试使用按钮单击上的文本框更新数据表中的记录。错误消息说不能插入重复值,并显示我输入到txtID的值。这是更新按钮的代码:

private void btnUpdate_Click(object sender, EventArgs e)
    {
        connection.Open();
        SqlCommand command = new SqlCommand();
        String query = "UPDATE Bug SET Tester_ID=" + txtID.Text + "',Tester_Name= '" + txtName.Text + "',Application_Name= '" + txtApp.Text + "',Class_Name= '" + txtClass.Text + "',Line_No= '" + txtLineNo.Text + "',Error_Description= '" + txtDesc.Text + "',Source_Code= '" + txtSource.Text + "',Status= '" + txtStatus.Text + "')";
        SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
        adapter.SelectCommand.ExecuteNonQuery();
        connection.Close();
        MessageBox.Show("Data Updated Successfully");
    }

1 个答案:

答案 0 :(得分:0)

您在该查询中没有where子句,因此它正在更新表中的所有记录,这会使某些记录重复。因此错误。 可能是由于您定义的表结构。

P.S。您应该查找SQL注入攻击,并应该参数化您的查询以避免它。

根据您的评论进行修改

String query = "UPDATE Bug Set Tester_Name= '" + txtName.Text + "',Application_Name= '" + txtApp.Text + "',Class_Name= '" + txtClass.Text + "',Line_No= '" + txtLineNo.Text + "',Error_Description= '" + txtDesc.Text + "',Source_Code= '" + txtSource.Text + "',Status= '" + txtStatus.Text + "' WHERE Tester_ID='" + txtID.Text + "'";

如果Tester_Id是数字,则不需要这些引号。

Where子句出现在Set。

之后

以下是参数化版本:

String query = "UPDATE Bug Set Tester_Name=@Tester_Name,Application_Name= @AppName,Class_Name= @Class_Name,Line_No= @Line_No,Error_Description= @Error_Description,Source_Code= @Source_Code,Status= @Status WHERE Tester_ID=@Tester_ID";

SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Tester_Name", "XYZ");
// other params
command.Parameters.AddWithValue("@Tester_ID", 10);