【问题标题】:Insert datetime2 into database将 datetime2 插入数据库
【发布时间】:2015-12-20 14:10:07
【问题描述】:

我使用datetime2 作为checkIncheckOut 的数据类型。以前我可以使用此代码添加到数据库中。

//value for checkIn = 12/25/2015 2:00:00 PM
checkIn = DateTime.ParseExact(Session["checkInDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture).AddHours(14);

//value for checkOut = 12/26/2015 12:00:00 PM
checkOut = DateTime.ParseExact(Session["checkOutDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture).AddHours(12);

strInsert = "INSERT INTO Reservation ( checkInDate, checkOutDate) VALUES (@checkInDate, @checkOutDate)";

cmdInsert = new SqlCommand(strInsert, conn);
cmdInsert.Parameters.AddWithValue("@checkInDate", checkIn);
cmdInsert.Parameters.AddWithValue("@checkOutDate", checkOut);

但现在它不起作用,我收到此错误;

"从字符转换日期和/或时间时转换失败 字符串”。

我认为错误是由包含“PM”和“AM”的签入值引起的,但这很奇怪,因为以前我可以将它添加到数据库中。

有人知道如何解决这个问题吗?

【问题讨论】:

  • 你确定你的两栏都是datetime2吗?在这种情况下,AddWithValue 可能 可能会产生问题。您是否曾尝试使用 Add 并指定您的参数类型?
  • 您会发布异常之前日期的值吗?
  • 标记了 MySQL 但 datetime2 是 SQL Server?
  • @AlexK。并使用SqlCommand :)
  • 作为最佳实践,尽可能不要使用AddWithValueblogs.msmvps.com/jcoehoorn/blog/2014/05/12/…

标签: c# sql sql-server datetime2


【解决方案1】:

您似乎想丢弃checkInDate 的时间部分。使用ParseExact 这样做并不是真正正确的方法。相反,您可以使用 DateTime 的 .Date 属性,然后添加小时数。

另外,为了避免.AddWithValue 带来的麻烦,只需使用.Add,所以...

string s = "12/25/2015 2:00:00 PM";
DateTime checkIn = DateTime.Parse(s, CultureInfo.GetCultureInfo("en-US")).Date.AddHours(14);
// ....
string strInsert = "INSERT INTO Reservation (checkInDate, checkOutDate) VALUES (@checkInDate, @checkOutDate)";

using (SqlConnection conn = new SqlConnection(connStr))
{
    using (SqlCommand cmdInsert = new SqlCommand(strInsert, conn))
    {
        cmdInsert.Parameters.Add(new SqlParameter("@checkInDate", SqlDbType.DateTime2).Value = checkIn);
        // ....
    }
}

请注意,您可以将 DateTime 存储在 Session 值中,无需将其存储为字符串。

我注意到您以美国日期格式 (MM/dd/yyyy) 引用了入住日期,但您在 .ParseExact 中的格式是“dd/MM/yyyy”。这也可能是麻烦的根源。

【讨论】:

    猜你喜欢
    • 2014-05-29
    • 1970-01-01
    • 2020-07-05
    • 2023-04-10
    • 2021-10-21
    • 2014-08-08
    • 2014-05-04
    相关资源
    最近更新 更多