C# 不使用空白字段更新sql数据库

C# 不使用空白字段更新sql数据库,c#,sql,winforms,C#,Sql,Winforms,我正在试图找到一种方法,使我的程序在点击提交表单时,如果某些字段为空,就不会更新sql数据库。现在,当我将其提交到sql数据库时,如果字段为空,它会将其更新为空。我的代码有没有办法不这样做 谢谢 //field names in the table string update = @"UPDATE Master_List SET Date_Complete1 = @Date_Complete1, Pass_Fail

我正在试图找到一种方法,使我的程序在点击提交表单时,如果某些字段为空,就不会更新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
            }
        }

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

如果您希望执行的任何检查失败,只需返回函数

If(string.IsNullOrEmpty(要检查的变量))
... 返回或配置用户的错误消息


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

如果要验证是否应该更改数据库字段属性以执行该任务。 如果要使用某些代码执行此操作,应添加如下内容:

   bool val = true;
      if (jobTxt.Text.Trim() == string.Empty) {
          val = false;
      }
if(val==true){
    command.ExecuteNonQuery();
}
else{
MessageBox.Show("Some field is empty")
}
如果要对每个文本框进行验证,请重复句子。 我希望这对你有帮助。
您可以在文本框上的else语句中指出哪个文本框为空。

如果一个或多个字段为空,则假设您要更新某些字段,则可以执行以下操作:

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语句中检查它们。

在升级数据库之前验证输入(控件的值)?如果数据库值不应为空,则数据库应具有约束。不要依赖前端来保持数据有效。首先从数据库检索对象,然后检查表单输入是否为空,然后用从数据库获取的对象值替换它们。顺便说一下,我建议使用实体框架。试试看..不要直接从文本框中选择。存储在局部变量中,然后使用
IsNullorBlank
检查参数名称应为“@Job\u Number”,依此类推。谢谢!这就是我要找的。