-2

//你好!每当我尝试使用 DatePicker 插入日期时,我都会遇到问题

       DateTime birth_date=Convert.ToDateTime(datePickerEBirthDate.SelectedDate);
            SqlConnection SQLconnection = new SqlConnection(@"Server=MyMachineName\SQLEXPRESS;Database=MyDataBase;Integrated Security=SSPI");
            SqlCommand command = SQLconnection.CreateCommand();
            SQLconnection.Open();
            command.CommandText = "INSERT INTO courses " +
            "(name, birthdate) VALUES " +
            "(@name, @birthdate)";
            command.Parameters.AddWithValue("@name", txtName.Text);
            command.Parameters.AddWithValue("@birthdate", birth_date);
            command.ExecuteNonQuery();
        SQLconnection.Close();

//这是错误信息 在此处输入图像描述

4

3 回答 3

1

就像您获取 TextBox.Text 属性 ( txtName.Text) 一样,您应该获取DatePicker.SelectedDate属性 ( dpSBirthDate.SelectedDate)。DataContext相反,您出于某种原因尝试转换?此外,您可以摆脱 Convert.ToDateTime(...) 调用,因为dpSBirthDate.SelectedDate它将返回一个 DateTime 对象。


更新(这是一个完全固定的代码部分):

var name = txtName.Text;
var birthdate = dpSBirthDate.SelectedDate;

using (var connection = new SqlConnection(@"Server=MyMachineName\SQLEXPRESS;Database=MyDataBase;Integrated Security=SSPI")
using (var command = connection.CreateCommand())
{
    command.CommandText = "INSERT INTO courses " +
                          "(name, birthdate) VALUES " +
                          "(@name, @birthdate)";

    if (name == null)
        throw new Exception("Name cannot be null.");
    if (!birthdate.HasValue)
        throw new Exception("Birthdate must contain a value.");

    command.Parameters.AddWithValue("@name", name);
    command.Parameters.AddWithValue("@birthdate", birthdate.Value);
    connection.Open();
    command.ExecuteNonQuery();
}

现在,如果此代码失败,它会告诉您原因……您的姓名或出生日期均无效。如果生日仍然无效,那么您必须在执行此代码之前检查 dpSBirthDate (the DatePicker) 是否设置为正确的 DateTime。希望有帮助。

另请注意,我通过添加 using 语句、异常处理和尽可能晚地打开连接来清理代码。

于 2012-06-07T15:13:00.173 回答
0

You should use datePickerEBirthDate.Value which will give you the datetime type so no need to convert to DateTime but you will end up with the time on that and might not want to search by this but that is your preference.

于 2012-06-07T15:42:12.827 回答
0

.NET 中的 DateTime 可以存储从 0001 年 1 月 1 日到 9999 年 12 月 31 日的日期。在 SQL 1753 年 1 月 1 日 - 9999 年 12 月 31 日。因此,0001 年 1 月 1 日到 1753 年 1 月 1 日之间的日期不能保存到数据库中。所以,检查解析的birth_date。可能你必须用正确的文化解析日期吗?

于 2012-06-07T15:19:37.773 回答