2011-05-30 78 views
2

我要插入日期時間變量爲DATETIME2類型的數據庫表列(從.NET程序) (IM使用SQLSERVER 2008,.NET 4.0,C#)如何.NET日期時間轉換到SQL Server DATETIME2

現在我有

 string insertCommand = @"INSERT INTO X VALUES (time.ToString()); 

問題是時間字符串格式。 SQL Server不能使用ToString()函數的輸出。我也試過.ToLongDate短日期等。 如何創建適當的sql命令以及如何格式化dateTime字符串以使其工作?

回答

1

您需要添加一個參數與DateTime值。

2

試試這個:

string sql = "insert into x values (@dt)"; 
SqlCommand cmd = cxn.CreateCommand(); 
cmd.CommandType = CommandType.Text; 
cmd.Parameters.AddWithValue("@dt", time); 
cmd.CommandText = sql; 
cn.Open(); 
cmd.ExecuteNonQuery(); 
cn.Close(); 
+0

考慮時間作爲C#的日期時間,當我這樣做時,只有日期存儲在數據庫中,而不是時間戳。這是爲什麼 ? – pordi 2016-02-04 11:52:09