不更新现有数据

时间:2013-09-23 09:47:02

标签: c# sql asp.net .net

使用此代码我正在执行更新...但每当我更新现有数据显示“记录更新”...这我不想...代表我想要记录不能更新becoz数据是已经存在......所以我怎么能这样做....帮助..

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();
    }
}

2 个答案:

答案 0 :(得分:1)

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

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);  

答案 1 :(得分:1)

尝试删除

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('record updated');", true);
来自你的阻止