简体   繁体   English

如何从C#将欧洲格式的日期和时间插入SQL Server?

[英]How to insert date and time in European format into SQL Server from C#?

Here's my query: 这是我的查询:

string sql = @"INSERT INTO MY_TABLE(DATE) 
                            VALUES (convert(datetime, '{0}')";

sql = string.Format(sql, myDate);

myDate is a C# DateTime object and has this value before the string.format : myDate是C# DateTime对象,在string.format之前具有此值:

在此处输入图片说明

MY_TABLE has a DATE column as a DateTime type. MY_TABLE具有一个DATE列作为DateTime类型。

I got this error: 我收到此错误:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. 从varchar数据类型到datetime数据类型的转换导致值超出范围。

I need to store the myDate value in a format like: 31/12/2013 23:59:00 into MY_TABLE. 我需要将myDate值以以下格式存储: 31/12/2013 23:59:00 31TABLE 2013年12月31日。

better to use sql parameters 更好地使用sql参数

string sql = @"INSERT INTO MY_TABLE(DATE) 
                            VALUES (@DATE)";

add the parameter to your SqlCommand with SqlParameterCollection.AddWithValue Method 使用SqlParameterCollection.AddWithValue方法将参数添加到SqlCommand中

command.Parameters.AddWithValue("@DATE", myDate);

OR, with SqlParameterCollection.Add Method 或,使用SqlParameterCollection.Add方法

   command.Parameters.Add("@DATE",SqlDbType.DateTime).Value = myDate
DateTime.Now.ToString("dd/MM/yyyy H:mm:ss")

For a list of the parameters see MSDN . 有关参数的列表,请参见MSDN (Scroll down a bit to see the table.) (向下滚动以查看表格。)

(And it is advised to use Parameters.AddWithValue to avoid SQL injection etc.) (建议使用Parameters.AddWithValue以避免SQL注入等。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM