【问题标题】:Correct DateTime format in SQL Server CE?SQL Server CE 中的正确日期时间格式?
【发布时间】:2012-08-15 10:08:38
【问题描述】:

我有一个 C#DateTime 类,想知道如何在 SQL Server CE 查询中对其进行格式化以将其插入数据库,我希望同时插入日期和时间。目前当我尝试其变体我得到无效的格式异常。

我当前使用的格式是:dd/MM/yyyy,希望做类似dd/MM/yyyy hh:mm:ss 的事情。

我尝试插入的方式是这样的:

 ( ( DateTime )_Value ).ToString( "dd/MM/yyyy hh:mm:ss" )

显然hh:mm:ss 不起作用,如果不存在dd/MM/yyyy 在查询中成功执行。

我尝试了几种格式,包括我在 google 上找到的格式,但到目前为止都没有奏效...

【问题讨论】:

  • 您能否附上您的代码,以便我们查看您的尝试?
  • 您是否能够将其他值插入数据库?遇到任何异常/错误?
  • 您要插入的字段类型是什么? SQL Server 中的 Date 和 DateTime 是有区别的。
  • 嗨@Jake1164,是的,我已经能够毫无问题地将其他值添加到他的数据库中,只是当我尝试添加时间时出现问题......
  • 尝试年-月-日,在它们之间使用“-”。时间格式相同 yyyy-MM-dd hh:mm:ss

标签: c# sql datetime sql-server-ce


【解决方案1】:

如果您完全不担心格式是否正确,那么您已经出了严重问题。要在任何数据库中正确使用日期时间值,您需要做两件事,而不仅仅是 sqlce:

  1. 确保您对列使用日期时间类型(而不是像 varchar 这样的文本类型)
  2. 确保在参数化查询中使用日期时间参数,而不是字符串连接。

如果您这样做,则不会涉及您的格式。完全没有。示例:

 void SetDate(int recordID, DateTime timeStamp)
 {
    string SQL = "UPDATE [sometable] SET someDateTimeColumn= @NewTime WHERE ID= @ID";

    using (var cn = new SqlCeConnection("connection string here"))
    using (var cmd = new SqlCeCommand(SQL, cn))
    {
        cmd.Parameters.Add("@NewTime", SqlDbType.DateTime).Value = timeStamp;
        cmd.Parameters.Add("@ID", SqlDbType.Integer).Value = recordID;

        cn.Open();
        cmd.ExecuteNonQuery();
    }
} 

从来没有EVER使用字符串操作将值替换为 sql 查询。这是一个巨大的禁忌。

【讨论】:

  • +1 指出不要使用字符串操作来存储日期。
  • +1 表示永远不要在 SQL 查询中使用字符串操作。
  • 你可以这样做吗:“UPDATE \@SomeTable SET \@SomeColumn ...等”
  • 堆栈溢出不允许我发布 at 符号,因此 \
【解决方案2】:

试试下面的格式:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")

【讨论】:

    【解决方案3】:

    伙计,你不需要将字符串转换为日期时间。

    使用新 DateTime 的实例并将日期作为参数传递。像这样:

    using (var ctx = new DBPreparoEntities())
    {
        var _client = from p in ctx.Client
                         select new Client
                         {
                             data = new DateTime(2016,08,17),
                             dateconf = null,
                             scod_cli = p.Rua,
                             valorini = 7214.62m,
                         };
        return client.ToList();
    }
    

    不要使用:

    ... data = DateTime.Parse("2016/12/10") // or other type convertions.
    

    【讨论】:

      【解决方案4】:
      private void button1_Click(object sender, EventArgs e)
      {
          var cnn1 ="";//connection string 
          SqlCeConnection cnn = new SqlCeConnection(cnn1);   
          datetime dt4 = DateTime.Today.Date.ToString("yyyyMMdd").trim();//format 
          var qry ="insert into tbl_test(User_Id, DateOfJoin)values (11,'" + dt4 + "')";
         
          cmd = new SqlCeCommand(qry, cnn);
         
          try
          {
              dr = cmd.ExecuteReader();
          }
          catch (Exception ex)
          {
              string sr = ex.Message;
              throw;
          }
      }
      

      以上代码对我有用。

      【讨论】:

      • 口头解释往往对其他人有帮助
      • //simply_pass _datetime _component _通过转换为格式化字符串
      【解决方案5】:

      对不起,这是在 vb.net 中,但这是我用来从 CE 日期/时间格式转换的方法:

      Public Shared Function ConvertSqlDateTimeFormat(ByVal s As String) As String
          Dim theDate As New Text.StringBuilder
          Dim sTemp As String = ""
          Dim iIndex As Integer
      
          If s.Length > 8 Then
              'first we do the time
              iIndex = s.IndexOf(" ", System.StringComparison.OrdinalIgnoreCase)
              If iIndex > 0 Then
                  sTemp = s.Substring(iIndex).Trim
                  iIndex = sTemp.IndexOf(".", System.StringComparison.OrdinalIgnoreCase)
                  If iIndex > 0 Then
                      sTemp = sTemp.Substring(0, iIndex)
                  End If
              End If
      
              'next the date
              theDate.Append(s.Substring(4, 2))
              theDate.Append("/")
              theDate.Append(s.Substring(6, 2))
              theDate.Append("/")
              theDate.Append(s.Substring(0, 4))
              theDate.Append(" ")
              theDate.Append(sTemp)
          End If
          Return theDate.ToString
      End Function
      

      【讨论】:

      • 您已经拥有这样一个等待调用的方法的想法是错误的。 sql 数据值的字符串操作在安全代码中没有位置。
      • 好的,那么安全漏洞在哪里呢?当然,我误解了这个问题,而是专注于将数据库中的日期转换为日期时间格式,而不是相反,但是如果数据已经在数据库中,我不确定问题是什么?如果 datetime.tryparse 没有给出正确的结果,你还有什么其他选择?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多