SQL Server CE中正确的DateTime格式? [英] Correct DateTime format in SQL Server CE?

查看:127
本文介绍了SQL Server CE中正确的DateTime格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C# DateTime 类,想知道我需要在SQL Server CE查询中格式化它以将其插入数据库,我希望有当前,当我尝试其它变体时,我会得到无效的格式异常。

I have a C# DateTime class and wanted to know how I need to format it in a SQL Server CE query to insert it into the database, I was hoping to have both the date and time inserted in. Currently when I try variations thereof I get invalid format exceptions.

我使用的当前格式是: dd / MM / yyyy ,希望能像 dd / MM / yyyy hh:mm:ss

Current format I'm using is: dd/MM/yyyy, was hoping to do something like dd/MM/yyyy hh:mm:ss.

我试图做插入的方式是这样的:

The way I'm trying to do the insert is like so:

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

显然 hh:mm:ss 不工作,如果没有,则$ / code> dd / MM / yyyy 在查询中成功执行。

Obviously hh:mm:ss isn't working, if that isn't there dd/MM/yyyy executes successfully in the query.

我尝试了一些格式,包括我在谷歌中发现的一些格式,但没有一个工作到目前为止...

I've tried a few formats including what I've found on google but none have worked so far...

推荐答案

如果您担心格式正确,某些事情已经严重错误。在数据库中正确使用datetime值有两件事情,而不仅仅是sqlce:

If you're worried about getting the format right at all, something has already gone seriously wrong. There are two things you need to do to correctly work with datetime values in any database, not just sqlce:


  1. 确保你使用列的日期时间类型(不是像varchar这样的文本类型)

  2. 确保在参数化查询中使用datetime参数,而不是字符串连接。

如果你这样做,你的部分没有格式化。在所有例如:

If you do that, there is no formatting involved on your part. At all. Example:

 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查询。这是一个巨大的 no-no。

Never ever ever ever EVER use string manipulation to substitute values into sql queries. It's a huge no-no.

这篇关于SQL Server CE中正确的DateTime格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆