[英]problems with insert datetime from calender in asp.net to microsoft sql
我正在嘗試從asp.net中的日歷中向Microsoft SQL數據庫插入所選日期。
當我選擇的時間像01/04/2012
其工作,而是試圖插入的時候30/01/2012
我得到的消息:
從char數據類型到datetime數據類型的轉換導致超出范圍的datetime值。
當我使用closeDateCalender.SelectedDate
創建datetime
對象時,c#中的代碼是:
sb.AppendFormat("Values('{0}', '{1}' ,'{2}', '{3}','{4}','{5}','{6}','{7}')",
opportunity.UserId,
opportunity.AccountId,
opportunity.OpportunityName,
opportunity.CloseDate,
opportunity.Stage,
opportunity.Probability,
opportunity.Amount,
opportunity.Description);
String prefix = "INSERT INTO Opportunities " + "([User_Id],Account_Id,Opportunity_Name,Close_Date,Stage,Probabilty,Amount,[Description])";
command = prefix + sb.ToString();
任何想法如何解決呢???
為了擺脫格式化等所有麻煩,請改用准備好的statemnts或參數化查詢,它將處理所有格式化問題。 就像是:
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
。
您的服務器設置為接受美國格式而不是歐洲日期。 如果您將日期重新格式化為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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.