0

如果我点击提交表单时某些字段为空白,我正在尝试为我的程序找出一种不更新 sql 数据库的方法。现在,当我将其提交到 sql 数据库时,如果字段为空白,它会将其更新为空白。有没有办法让我的代码不这样做?

谢谢

        //field names in the table
        string update = @"UPDATE Master_List
                        SET Date_Complete1 = @Date_Complete1, Pass_Fail = @Pass_Fail, CRC_Number = @CRC_Number, QN_Number = @QN_Number, Notes = @Notes WHERE Job_Number = @Job_Number"; //parameter names

        using (SqlConnection conn = new SqlConnection(connString)) //using allows disposing of low level resources
        {
            try
            {
                conn.Open();//open new connection
                command = new SqlCommand(update, conn); // create the new sql command object
                                                        // Read value from form and save to the table
                command.Parameters.AddWithValue(@"Job_Number", jobTxt.Text);
                command.Parameters.AddWithValue(@"Pass_Fail", comboBox1.Text);
                command.Parameters.AddWithValue(@"Date_Complete1", opBox1.Text);
                command.Parameters.AddWithValue(@"CRC_Number", crcTxt.Text);
                command.Parameters.AddWithValue(@"QN_Number", qnTxt.Text);
                command.Parameters.AddWithValue(@"Notes", notesTxt.Text);
                command.ExecuteNonQuery(); // Push form into the table
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); // If there is something wrong, show the user message
            }
        }
4

3 回答 3

1

假设您想在一个或多个字段为空白时更新某些字段,那么您可以这样做:

UPDATE Master_List
SET Date_Complete1 = ISNULL(NULLIF(@Date_Complete1,''),Date_Complete1),
    Pass_Fail = ISNULL(NULLIF(@Pass_Fail,''),Pass_Fail),
    CRC_Number = ISNULL(NULLIF(@CRC_Number,''),CRC_Number),
    QN_Number = ISNULL(NULLIF(@QN_Number,''),QN_Number),
    Notes = ISNULL(NULLIF(@Notes,''),Notes)
WHERE Job_Number = @Job_Number

如果您不希望在任何字段为空白时更新任何字段,则只需在 if 语句中检查它们。

于 2019-10-22T22:12:53.267 回答
0

在执行 sql 代码之前对输入数据进行检查。

如果您想做的任何检查失败,只需退出函数即可,例如

If(string.IsNullOrEmpty(variable to check)) ...为用户返回或配置错误消息...

或者执行一些逻辑来向用户显示您不想要空白字段。

于 2019-10-22T21:28:39.557 回答
0

如果您要验证是否应该更改数据库字段属性以执行该任务。如果你想用一些代码来做到这一点,你应该添加这样的东西:

   bool val = true;
      if (jobTxt.Text.Trim() == string.Empty) {
          val = false;
      }
if(val==true){
    command.ExecuteNonQuery();
}
else{
MessageBox.Show("Some field is empty")
}

如果要对每个文本框进行验证,请重复该句子。我希望这对你有帮助。您可以在文本框上的 else 语句中说出哪个文本框是空的。

于 2019-10-22T21:50:21.123 回答