更新查询不引发错误

我在这里先向您的帮助表示感谢。


我正在尝试在C#中使用更新查询


错误:即使我使用了不正确的值,命令也正在执行


设计视图 代码:


protected void Button1_Click(object sender, EventArgs e)

{

    try

    {

        con.Open();


        cmd = new SqlCommand("update Comcast_AvayaID set Status='Inactive' where Employee_Id='" + TxtEMPID.Text + "' and AvayaID ='" + TxtAvayaID.Text + "'", con);

        cmd = new SqlCommand("UPDATE Avaya_Id SET Status = 'UnAssigned' where Avaya_ID ='" + TxtAvayaID.Text + "'", con);

        cmd.ExecuteNonQuery();

        LBLSuccess.Visible = true;

        LBLSuccess.Text = "Deactivation Successfull";

        con.Close();

    }

    catch (SqlException ex)

    {

        LBLSuccess.Visible = true;

        LBLSuccess.Text = "Deactivation Unsuccessfull";

    }


慕田峪7331174
浏览 157回答 2
2回答

慕田峪4524236

您的代码看起来会像这样更好,它不是最佳的,但是与片段相比,它已经是一种更好的代码了1)使用辅助函数添加参数以解决sql注入问题2)ExecuteNonQuery返回受影响的行,因此如果您希望更新1行,则可以检查该行3)如果使用不存在的id更新行,则不会像您在代码中所期望的那样抛出SqlException,例如,发生锁定时 public void Update()        {            var con = new SqlConnection();            try            {                var empId = TxtEMPID.Text                var avayaId = TxtAvayaID.Text                con.Open();                var cmd1 = new SqlCommand("update Comcast_AvayaID set Status='Inactive' where Employee_Id=@empId and AvayaID = @avayaId", con);                              cmd1.Parameters.Add(AddParameter("@empId",empId));                cmd1.Parameters.Add(AddParameter("@avayaId", avayaId));                var cmd2 = new SqlCommand("UPDATE Avaya_Id SET Status = 'UnAssigned' where Avaya_ID =avayaId", con);                cmd2.Parameters.Add(AddParameter("@avayaId", avayaId));                var rowsaffected1 = cmd1.ExecuteNonQuery();                var rowsAffected2 = cmd2.ExecuteNonQuery();                if (rowsaffected1 == 1 && rowsAffected2 == 1)                {                    //success code goes here                    //--------                    LBLSuccess.Visible = true;                    LBLSuccess.Text = "Deactivation Successfull";                }                else                {                    // failure code goes here                    //-----------------------                    LBLSuccess.Visible = true;                    LBLSuccess.Text = "Deactivation Unsuccessfull";                }            }            catch (SqlException ex)            {                //handle errors            }            finally            {                con.Close();            }            Console.ReadLine();        }        private SqlParameter AddParameter(string name, object value) {            var par = new SqlParameter();            par.ParameterName = name;            par.Value = value;            return par;        }

凤凰求蛊

如果您输入“不正确”的值,它只会更新零个记录。这里没有错误/异常。
打开App,查看更多内容
随时随地看视频慕课网APP