代码之家  ›  专栏  ›  技术社区  ›  Spyros

数据库中的日期时间类和日期时间

  •  0
  • Spyros  · 技术社区  · 15 年前

    我有以下问题。

    我有一个具有一些datetime属性的对象,以及一个数据库中存储所有这些对象的表,在SQL Server中,我希望将datetime属性存储在datetime数据类型的某些列中,但SQL Server中datetime的格式不同于C中的datetime类,并且我得到一个SQL异常,说“无法分析datetime”。我知道如何通过使格式为YYYY-MM-DD来解决这个问题,但是这是正确和最好的解决方案吗?

    public void UpdateInvitation(string ownerId, string couponKey, string status, string invitedEmail, DateTime? sentDate, DateTime? redeemedDate)
        {
            using (var con = new SqlConnection(this.ConnectionString))
            {
                try
                {
                    con.Open();
                    var command =
                            new SqlCommand(
                                    "UPDATE INVITATIONS SET Status='@status', InvitedEmail='@invitedEmail', SentDate='@sentDate', RedeemDate='@redeemedDate' WHERE CouponKey='@CouponKey' AND OwnerId='@OwnerId'");
                    var ownerIdParam = new SqlParameter("@ownerId", ownerId);
                    var couponKeyParam = new SqlParameter("@couponKey", couponKey);
                    var statusParam = new SqlParameter("@status", status);
                    var invitedEmailParam = new SqlParameter("@invitedEmail", invitedEmail);
                    var sentDateParam = new SqlParameter("@sentDate", sentDate.Value) { SqlDbType = SqlDbType.DateTime };
                    var redeemedDateParam = new SqlParameter("@redeemedDate", redeemedDate.Value) { SqlDbType = SqlDbType.DateTime };
                    command.Parameters.AddRange(new[]
                                                {
                                                        ownerIdParam, couponKeyParam, statusParam, invitedEmailParam,
                                                        sentDateParam, redeemedDateParam
                                                });
                    command.Connection = con;
                    var rowsAffected = command.ExecuteNonQuery();
                    Log.DebugFormat("Invitation updated for owner id : [{0}] with key {1}, {2} rows affected", ownerId,
                                    couponKey, rowsAffected);
                }
                catch (Exception exception)
                {
                    throw new InvitationDataContextException(exception);
                }
            }
        }
    
    3 回复  |  直到 15 年前
        1
  •  7
  •   Arthur    15 年前

    没有引号

    new SqlCommand("UPDATE INVITATIONS SET Status=@status, InvitedEmail=@invitedEmail, SentDate=@sentDate, ...
    
        2
  •  0
  •   Bobby    15 年前

    好吧,不看你的代码,我建议你开始使用 Parameterized Queries .

        3
  •  0
  •   mattmc3    15 年前

    如果您使用的是SQL Server 2008,则新的datetime2数据类型将直接映射到.NET datetime对象。如果您一直在使用SQL的旧日期时间字段,请注意不要传递超出范围的日期,否则会出现运行时错误。尝试插入datetime.minValue是一个常见错误。