【发布时间】:2019-10-22 21:11:45
【问题描述】:
如果我点击提交表单时某些字段为空白,我正在尝试为我的程序找出一种不更新 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
}
}
【问题讨论】:
-
在更新数据库之前验证输入(控件的值)?
-
如果数据库值不应该为空,那么数据库应该有一个约束。不要依赖前端来保持数据有效。
-
首先从数据库中检索对象,然后检查表单输入是否为空,然后将它们替换为从数据库中获取的对象值。顺便说一句,我推荐使用实体框架。试一试..
-
不要直接从 textbox.store 中选择一个局部变量然后使用
IsNullorBlank进行检查 -
参数名称应为“@Job_Number”等。