Wednesday, July 12, 2006

How do I enter a null date into the database?

Make sure that the System.Data.Namespace is included.

include System.Data.SqlType;

In the command parameters to be parsed into database, use SqlDateTime.Null:






public void InsertDateOfBirth(string Date1){
SqlConnection cn = new SqlConnection();
string sqlstring = "Insert into Database1 values (@birthday)";
SqlCommand cmd = new SqlCommand(sqlstring, cn);
cmd.Parameters.Add("@birthday", SqlDbType.DateTime);
try
{
cmd.Parameters["@birthday"].Value = DateTime.Parse(Date1);
}
catch (Exception er)
{
cmd.Parmeters["@birthday"].Value = SqlDateTime.null;
}
try
{
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
catch (SqlException sqlerror)
{
Console.WriteLine(sqlerror.Message);
}
catch (Exception er1)
{
Console.WriteLine(er1.Message);
}
}

No comments:

Post a Comment