You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#更新SQL Server Customer表的If-Else判断逻辑如何修正

代码调整方案

你原有代码存在三个核心问题:

  • 直接拼接SQL语句存在SQL注入风险,必须改为参数化查询
  • 校验逻辑顺序错误,应该先做本地数值校验,再做数据库层面的客户存在性校验,全部通过后再执行更新操作
  • 错误混用ExecuteNonQuery和ExecuteScalar方法,语法层面存在未完成的空判断表达式

调整后的完整代码如下:

private void btnChange_Click(object sender, EventArgs e)
{
    // 第一步:先本地校验积分是否为合法数值
    if (!int.TryParse(textMembershipPoint.Text, out int membershipPoint))
    {
        MessageBox.Show("Invalid Membership Point. Only Number Allowed.");
        return;
    }

    con.Open();
    try
    {
        // 第二步:校验客户姓名是否存在
        SqlCommand checkCmd = con.CreateCommand();
        checkCmd.CommandType = CommandType.Text;
        checkCmd.CommandText = "SELECT COUNT(*) FROM Customer WHERE NameCustomer = @NameCustomer";
        checkCmd.Parameters.AddWithValue("@NameCustomer", textNameCustomer.Text);
        int customerCount = (int)checkCmd.ExecuteScalar();
        if (customerCount == 0)
        {
            MessageBox.Show("Invalid Name of Customer.");
            return;
        }

        // 第三步:所有校验通过,执行更新
        SqlCommand updateCmd = con.CreateCommand();
        updateCmd.CommandType = CommandType.Text;
        updateCmd.CommandText = "UPDATE Customer SET MembershipPoint = @MembershipPoint WHERE NameCustomer = @NameCustomer";
        updateCmd.Parameters.AddWithValue("@MembershipPoint", membershipPoint);
        updateCmd.Parameters.AddWithValue("@NameCustomer", textNameCustomer.Text);
        updateCmd.ExecuteNonQuery();
        
        MessageBox.Show("Membership Point is changed.");
        textMembershipPoint.Text = membershipPoint.ToString();
    }
    finally
    {
        // 保证数据库连接始终会被关闭,避免连接泄漏
        con.Close();
    }

    display_data();
}

如果你的MembershipPoint字段存储的是小数类型,把代码里的int.TryParse替换为decimal.TryParse即可。

内容的提问来源于stack exchange,提问作者user17166745

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:36:03