繁体   English   中英

当我单击更新按钮以更新SQL C#中的数据库值时,所有行都受到相同值的影响

[英]When i click the update button to update database values in SQL C# All Rows Are Affected by the same value

这是我的屏幕截图

波纹管是我的代码更新按钮单击事件!

    {
        try
    {

        con = new SqlConnection(cs.ConDB);
        con.Open();
        string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "'";
        cmd = new SqlCommand(cb);
        cmd.Connection = con;
        cmd.ExecuteReader();
        con.Close();
        MessageBox.Show("Successfully updated", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);

        btnUpdate.Enabled = false;
        btnSave.Enabled = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    try
    {
        con = new SqlConnection(cs.ConDB);
        con.Open();
        cmd = new SqlCommand("SELECT * From tblFees", con);
        SqlDataAdapter myDA = new SqlDataAdapter(cmd);
        DataSet myDataSet = new DataSet();
        myDA.Fill(myDataSet, "tblFees");
        dataGridView1.DataSource = myDataSet.Tables["tblFees"].DefaultView;
        con.Close();


    }catch (Exception ex)
        {
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,                          MessageBoxIcon.Error);}`

请解决我的问题,我是编程领域的新手,我们将不胜感激

您应该使用where条件指定行

例如,您可以修改查询,如下所示。 我假设cboUser是一个组合框,您可以在其中选择特定用户,以便仅针对该选定用户更新数据。

SqlConnection con = new SqlConnection();
con.Open();
string cb = "Update [tblFees] set Salutation=@Salutation, Name=@Name,Sex =@Sex where tblFeesPK=@pk'";
SqlCommand cmd = new SqlCommand(cb, con);
cmd.Parameters.AddWithValue("@Salutation", cmbSalutation.Text);
cmd.Parameters.AddWithValue("@Name", tbName.Text);
cmd.Parameters.AddWithValue("@Sex", cmbSex.Text);
cmd.Parameters.AddWithValue("@pk", cboUser.SelectedValue);
cmd.ExecuteNonQuery();

如果要基于名称更新详细信息,则意味着:可以在where条件中给出名称。 但这不是正确的方法。 因此请使用主键(因为名称可能具有重复值)

您需要将语句更改为:

string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "' where Name= '" + tbName.Text + "'";

您需要在where Name= '" + tbName.Text + "';添加where Name= '" + tbName.Text + "';

现在它将更新名称匹配的那些行

同样不幸的是,您应该使用参数化查询

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM