簡體   English   中英

如何將asp.net c#中的datetime屬性插入sql server中的日期列?

[英]How to insert datetime property from asp.net c# to a date column in sql server?

我在使用日歷控件時遇到問題..我在文本框中獲取日期...我必須將其插入到數據庫中...使用帶有c#的asp.net

在我的Web應用程序中,field屬性設置為datetime ,在表中列的數據類型為date

我怎樣才能做到這一點??

我得到的錯誤是:

將varchar數據類型轉換為日期時間數據類型會導致超出范圍的值。 該語句已終止。

在這方面有人能幫助我嗎?

提前致謝

我得到的錯誤是:將varchar數據類型轉換為日期時間數據類型導致超出范圍的值。

聽起來你正試圖將它作為一個字符串插入,這通常是個壞主意。 您應該使用參數化SQL並將值設置為參數,仍然作為.NET DateTime 有關參數化SQL的示例,請參閱SqlCommand.Parameters的文檔。 您應該始終盡可能長時間地保留數據的自然類型。

當然,如果您嘗試插入超出SQL可以存儲的范圍的DateTime值,則仍然可能會出現此錯誤。 特別是,我認為SQL的年度下限為1753。 如果由於某種原因(1月1日,1AD)你的值是DateTime.MinValue ,那么你仍然會遇到這個問題。 您是否為要插入的值添加了診斷信息?

對不起,我的第一個回答錯過了你的問題 嘗試使用標准參數系統添加參數。

command.CommandText =“INSERT INTO FooTable(FooDate)VALUES(@FooDate)”; command.Parameters.AddWithValue(“@ FooDate”,DateToUse.Date);

使用.Date只會返回對象的日期部分。 這是對Date Date和DateTime的另一個引用

如果您正在使用參數化查詢 ,我毫不費力地將ASP.NET日歷控件中的DateTime插入到包含DATE類型列的SQL Server數據庫表中。

使用這樣的東西:

// define INSERT statement - of course, yours will look quite different!
string insertStmt = "INSERT INTO dbo.DateTest(TheDate) VALUES(@DateValue);";

// set up connection and SqlCommand to do insert
using(SqlConnection conn = new SqlConnection("....your-connection-string-here...."))
using (SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
     // add the parameters - the @DateValue - to the SqlCommand object and
     // define it's datatype (on the database) and set the value to be stored
     cmd.Parameters.Add("@DateValue", SqlDbType.Date).Value = Calendar1.SelectedDate;

     // open connection, execute command, close connection
     conn.Open();
     cmd.ExecuteNonQuery();
     conn.Close();
}

首先嘗試一件事,嘗試在列中插入01/01/2012,因為這可能是因為錯誤的文化....它可能是mm / dd / yyyy或dd / mm / yyyy

首先嘗試這個01/01/2012,看看那是否有效。

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM