【问题标题】:DateTime problem in sql compactsql compact 中的日期时间问题
【发布时间】:2010-03-09 13:41:56
【问题描述】:

我使用 Sql Compact3.5 作为我的数据库和 C# .NET 在不同的系统中,我得到的日期时间格式不同。在 Windows XP 中,它以以下格式检索日期时间:MM-dd-yyyy HH:mm:ss,在媒体中心中,它以以下格式检索:MM/dd/yyyy hh:m:ss。有什么方法可以使日期时间格式不受文化影响,或者我可以在 sql compact 中设置日期时间格式,所以让它成为任何只使用该格式的 PC 吗???

例子:

//TimeOfCall is passed as String using the format DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
    using (SqlCeCommand SqlceCmd = new SqlCeCommand(
         "Insert into myreports(TimeOfCall,Status) values(?,?)", con))
    {
        if (con.State == ConnectionState.Closed)
            con.Open();
        SqlceCmd.Parameters.Add(new SqlCeParameter("@TimeOfCall", strTimeOfCall));
        SqlceCmd.Parameters.Add(new SqlCeParameter("@Status", strStatus));

        int RowsaAffected = SqlceCmd.ExecuteNonQuery();
        con.Close();
        return RowsaAffected;
    }
}

在重新检索记录时,以这种方式使用查询:

//FromTime and ToTime are passeed in the same format as while storing
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
    using (SqlCeDataAdapter SqlceDA = new SqlCeDataAdapter("Select TimeOfCall from myreports where TimeOfCall between '" + strFromTime + "' and '" + strToTime + "' order by TimeOfCall", con))
    {
        if (con.State == ConnectionState.Closed)
            con.Open();
        SqlceDA.Fill(dtReports);
        con.Close();
        return dtReports;
    }
}

我希望它很清楚

【问题讨论】:

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


    【解决方案1】:

    好的,从代码来看,你基本上是以错误的方式做正确的事。

    好消息是您正在使用参数 - 这是完全正确的 - 但是您实际上不需要 不想 在设置参数值之前将日期转换为字符串。

    最简单的应该是将SqlceCmd.Parameters.Add(new SqlCeParameter("@TimeOfCall", strTimeOfCall)); 更改为SqlceCmd.Parameters.AddWithValue("@TimeOfCall", timeOfCall));,其中timeOfCall 是一个日期时间值。

    如果状态本身不是字符串,这同样适用于状态。

    如果您想更明确地了解类型,请先创建参数定义类型,然后再设置它。

    对于您的选择查询做同样的事情,用参数@fromTime 和@toTime 替换您的字符串连接,并直接从适当的日期时间值设置参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多