如何将空值插入sql日期字段

问题描述 投票:1回答:2

我正在制作一个项目,将大象的数据插入到它的数据库的保护中心。在其中我假设有些大象出生在其中,而有些大象有天赋。所以我希望将两种日期保存到数据库中。当一头大象出生时,它应该只有一个生日,就像大象有天赋一样,它应该有两个日期,分别是到达日期和生日。

我编写了插入查询。

            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);
        }

在这里,我在保存日期时遇到了问题。如果我想保存出生在中心的大象,它应该没有到达日期。所以我忽略了到达日期选择器并将详细信息保存到数据库中。当我在数据库中查看数据时,默认值将保存到到达日期。

enter image description here

我需要通过向它插入一个空值来保持到达日期列为空。我该怎么做?

sql .net
2个回答
1
投票

首先,从.NET创建查询不是一个好习惯。代替,

  1. 使用Query并将值作为参数传递给SqlCommand,或
  2. 使用存储过程并将值作为参数传递给SqlCommand
  3. 或者,您可以使用现有方法并传递null,如:

string save_emp_query =“INSERT INTO ElephantData VALUES('”+ txtidentyno.Text +“','”+ txtelname.Text +“','”+ cmbspecies.Text +“','”+ gen +“','”+ med +“','”+ dtpdob.Text +“',null,'”+ cmbcon.Text +“')”

如果您可以按照方法1和2进行操作,可以参考以下代码:

// 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();

0
投票

也许你需要这样的条件

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 + "')";
}
© www.soinside.com 2019 - 2024. All rights reserved.