C# 从asp.net中的日历向microsoft sql插入日期时间时出现问题
我正在尝试将asp.net中日历中的选定日期插入Microsoft SQL数据库 当我选择时间时,比如C# 从asp.net中的日历向microsoft sql插入日期时间时出现问题,c#,asp.net,sql,sql-server,C#,Asp.net,Sql,Sql Server,我正在尝试将asp.net中日历中的选定日期插入Microsoft SQL数据库 当我选择时间时,比如01/04/2012它的工作,但是当我尝试插入30/01/2012时,我得到了一条信息: 将char数据类型转换为datetime数据类型会导致 超出范围的日期时间值 当我使用closeDateCalender.SelectedDate创建datetime对象时, c#中的代码是: 你知道怎么解决吗?你的服务器设置为接受美式而非欧式的日期。如果重新设置日期格式,使其采用yyyy-MM-dd格式,
01/04/2012
它的工作,但是当我尝试插入30/01/2012
时,我得到了一条信息:
将char数据类型转换为datetime数据类型会导致
超出范围的日期时间值
当我使用closeDateCalender.SelectedDate
创建datetime
对象时,
c#中的代码是:
你知道怎么解决吗?你的服务器设置为接受美式而非欧式的日期。如果重新设置日期格式,使其采用
yyyy-MM-dd
格式,则可以使用
试试这个:
sb.AppendFormat("Values('{0}', '{1}' ,'{2}', '{3}','{4}','{5}','{6}','{7}')",
opportunity.UserId,
opportunity.AccountId,
opportunity.OpportunityName,
opportunity.CloseDate.ToString("yyyy-MM-dd"),
opportunity.Stage,
opportunity.Probability,
opportunity.Amount,
opportunity.Description);
为了摆脱格式化和其他事情带来的所有痛苦,请改用预处理语句或参数化查询,它将处理所有这些格式化内容。比如:
string YourSQL = "INSERT INTO Tablename(columns list) Values(?, ?, ?, ..) ";
command.Parameters.Add("CloseDate",
DbType.DateTime).Value = opportunity.CloseDate;
...
...// do the same for the rest of the fields.
这样,opportunity.CloseDate
的数据类型应为DateTime
string YourSQL = "INSERT INTO Tablename(columns list) Values(?, ?, ?, ..) ";
command.Parameters.Add("CloseDate",
DbType.DateTime).Value = opportunity.CloseDate;
...
...// do the same for the rest of the fields.