【问题标题】:C# DateTime Class and Datetime in databaseC# DateTime 类和数据库中的日期时间
【发布时间】:2010-06-18 06:51:34
【问题描述】:

我有以下问题。

我有一个带有一些 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);
            }
        }
    }

【问题讨论】:

  • 你能不能。你正在使用的代码?尤其是您在代码中使用的 SQL 语句。
  • 你能粘贴你用过的代码吗?

标签: c# sql database sql-server-2005 datetime


【解决方案1】:

没有引号

new SqlCommand("UPDATE INVITATIONS SET Status=@status, InvitedEmail=@invitedEmail, SentDate=@sentDate, ...

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • @Spyros:那么你不应该看到这个问题。请张贴代码。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 2021-01-22
      相关资源
      最近更新 更多