不更新现有数据

本文关键字:数据 更新 | 更新日期: 2023-09-27 18:32:27

使用此代码,我正在执行更新...但是每当我使用现有数据更新时,都会显示"记录已更新"......这个我不要...为此,我希望记录无法更新,因为数据已经存在...那我该怎么做....帮助。。

protected void Button2_Click(object sender, EventArgs e)//Update
{
    if (TexBo_num.Text == ""  &&  TexBo_num.Text != "contact_no" )
    {
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('contact number not be empty');", true);
    }
    else if(TxtBox_name.Text=="name" && TexBo_add.Text=="address" && TexBo_num.Text=="contact_no")
    {
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('can't update the same record');", true);
    }else
    {
        SqlConnection con = new SqlConnection(@"Data Source=SYSTEM2'SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True");
        SqlCommand cmd = new SqlCommand("UPDATE detail SET name='" + TxtBox_name.Text + "',address='" + TexBo_add.Text + "',contact_no='" + TexBo_num.Text + "' WHERE contact_no='" + TexBo_num.Text + "'", con);
        con.Open();
        cmd.ExecuteNonQuery();
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('record updated');", true);
        con.Close();
    }
}

不更新现有数据

如果您不希望显示该消息,请删除以下行:

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('record updated');", true);

此外,请使用参数化查询,因为容易受到 SQL 注入攻击。

cmd.CommandText = "UPDATE detail SET name=@name,address=@address,contact_no=@contactno WHERE contactno = @contactno");
cmd.Parameters.AddWithValue("@name", TxtBox_name.Text);  
cmd.Parameters.AddWithValue("@address", TxtBo_add.Text);  
cmd.Parameters.AddWithValue("@contactno", TexBo_num.Text);  

尝试删除

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('record updated');", true);

从您的 else 块