如何在sql日期字段中插入空值
我正在做一个项目,将保护中心大象的数据插入到它的数据库中。在这个项目中,我假设有些大象出生在保护中心,而有些大象有天赋。因此,我希望将两种日期保存到数据库中。当大象出生时,它应该只有一个象有天赋的生日,它应该有两个日期,分别是到达日期和生日 我已经对插入查询进行了编码如何在sql日期字段中插入空值,sql,.net,Sql,.net,我正在做一个项目,将保护中心大象的数据插入到它的数据库中。在这个项目中,我假设有些大象出生在保护中心,而有些大象有天赋。因此,我希望将两种日期保存到数据库中。当大象出生时,它应该只有一个象有天赋的生日,它应该有两个日期,分别是到达日期和生日 我已经对插入查询进行了编码 try { if (rbm.Checked == true) { gen = "Male";
try
{
if (rbm.Checked == true)
{
gen = "Male";
}
else if (rbf.Checked == true)
{
gen = "Female";
}
if (rbgr.Checked == true)
{
med = "gifres";
}
else if (rbb.Checked == true)
{
med = "born";
}
String save_emp_query = "INSERT INTO ElephantData VALUES('" + txtidentyno.Text + "','" + txtelname.Text + "','" + cmbspecies.Text + "','" + gen + "','" + med + "','" + dtpdob.Text + "','" + dtpdoa.Text + "','" + cmbcon.Text + "')";
cmd = new SqlCommand(save_emp_query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Elephant " + txtelname.Text + " (" + txtidentyno.Text + ") successfully saved to the database!", "Saved!", MessageBoxButtons.OK, MessageBoxIcon.Information);
clear();
}
catch (Exception ex)
{
MessageBox.Show("Error while Saving....." + Environment.NewLine + ex);
}
在这里,我在保存日期时遇到了一个问题。如果我想保存出生在中心的大象,它不应该有到达日期。因此,我忽略到达日期选择器并将详细信息保存到数据库中。当我在数据库中查看数据时,默认值保存到到达日期
我需要在到货日期列中插入一个空值,以将其保留为空。我如何才能做到这一点?也许您需要这样的条件
if(dtpdoa.Text == ''){
String save_emp_query = "INSERT INTO ElephantData VALUES('" + txtidentyno.Text + "','" + txtelname.Text + "','" + cmbspecies.Text + "','" + gen + "','" + med + "','" + dtpdob.Text + "',null,'" + cmbcon.Text + "')";
}else{
String save_emp_query = "INSERT INTO ElephantData VALUES('" + txtidentyno.Text + "','" + txtelname.Text + "','" + cmbspecies.Text + "','" + gen + "','" + med + "','" + dtpdob.Text + "','" + dtpdoa.Text + "','" + cmbcon.Text + "')";
}
首先,从.NET创建查询不是一个好的做法。 相反
// 1. declare command object with parameter
SqlCommand cmd = new SqlCommand(
"INSERT INTO ElephantData VALUES(@IdNo, @Species ....., conn);
// 2. define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "@IdNo";
param.Value = txtidentyno.Text;
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "@Species";
param2.Value = cmbspecies.Text;
// 3. add new parameter to command object
cmd.Parameters.Add(param);
// 4. Finally Execute Query
cmd.ExecuteNonQuery();
不要连接你的值,使用参数。我该怎么做,你能给我一个示例代码吗?网上有太多的示例(在这个网站和更广泛的网络上),请自己搜索和尝试。我用了你建议的第一种方法,非常有效。谢谢!好@akila ranasingha,你采用了更好的方法。请您投票并将其标记为答案,以便更好地帮助社区找到解决方案。