[英]Inserting DateTime into Sql Server 2005
我在將日期時間格式變量插入Sql Server 2005數據庫時遇到問題。 日期時間格式為dd.MM.yyyy
conn.Open();
string conString = "SET DATEFORMAT DMY INSERT INTO AmortPlanT (InvestmentID,StartDate,Maturity,IRate,CoupPerYear,parValue) Values (@IIndex,'@StartDate','@Maturity',@IRate,@CouponPerYear,@parValue)";
using (SqlCommand myCommand = new SqlCommand(conString, conn))
{
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Add("@IIndex", SqlDbType.Int).Value = investmentIndex;
myCommand.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
myCommand.Parameters.Add("@Maturity", SqlDbType.DateTime).Value = maturity;
myCommand.Parameters.Add("@IRate", SqlDbType.Float).Value = iRate;
myCommand.Parameters.Add("@CouponPerYear", SqlDbType.Int).Value = coupPerYear;
myCommand.Parameters.Add("@parValue", SqlDbType.Float).Value = parValue;
myCommand.ExecuteNonQuery();
}
StartDate和Maturity是我從dateTimePicker.Value獲得的DateTime變量。
而且我總是得到錯誤:
從字符串轉換日期時間時轉換失敗。
謝謝您的幫助。
您不應該將參數用引號引起來。這是正確的查詢。
values子句中的'@StartDate'是錯誤的,應該只是@StartDate ...如下所述...
conn.Open();
string conString = "SET DATEFORMAT DMY INSERT INTO AmortPlanT
(InvestmentID,StartDate,Maturity,IRate,CoupPerYear,parValue) Values
(@IIndex,@StartDate,@Maturity,@IRate,@CouponPerYear,@parValue)";
using (SqlCommand myCommand = new SqlCommand(conString, conn))
{
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Add("@IIndex", SqlDbType.Int).Value = investmentIndex;
myCommand.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
myCommand.Parameters.Add("@Maturity", SqlDbType.DateTime).Value = maturity;
myCommand.Parameters.Add("@IRate", SqlDbType.Float).Value = iRate; myCommand.Parameters.Add("@CouponPerYear", SqlDbType.Int).Value = coupPerYear;
myCommand.Parameters.Add("@parValue", SqlDbType.Float).Value = parValue; myCommand.ExecuteNonQuery();
}
問題是您在考慮字符串方面的問題...
日期時間格式為dd.MM.yyyy
不,不是;不是。 DateTime
的格式(當作為參數傳遞時)實際上只是一個二進制數; -p( startDate
應該是DateTime
,而不是string
)。
使用參數時,不要包含字符串標記( '
)-否則是指“字符串'@name'
”,而不是“參數@name
包含的字符串”; 嘗試刪除它們:
string conString = @"
SET DATEFORMAT DMY INSERT INTO AmortPlanT (InvestmentID,StartDate,Maturity,IRate,CoupPerYear,parValue)
VALUES (@IIndex,@StartDate,@Maturity,@IRate,@CouponPerYear,@parValue)";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.