2010-10-03 63 views
3

環境 單聲道和PostgreSQL,淨MVC中,Windows淨DateTime.Now VS PostgreSQL的時間戳比較

我試圖證明在未來發生的所有事件。

爲了做到這一點,我使用的SQL語句:

NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM dinners WHERE EventDate >= " + DateTime.Now, dinnerConn); 

現在,如果我比較DateTime.Now和我EVENTDATE時間戳從數據庫中,我得到以下

(EventDate) 12/18/2010 7:00:00 PM - (DateTime.Now) 10/2/2010 7:59:48 PM 

他們似乎很容易比較給我,但每當我運行此查詢,我得到如下:

ERROR: 42601: syntax error at or near "8" 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: Npgsql.NpgsqlException: ERROR: 42601: syntax error at or near "8" 

Source Error: 


Line 106:   try 
Line 107:   { 
Line 108:    NpgsqlDataReader reader = command.ExecuteReader(); 
Line 109:    while (reader.Read()) 
Line 110:    { 

Source File: c:\Documents and Settings\Andrew\My Documents\Visual Studio 2008\Projects\MvcApplication1\MvcApplication1\Models\DBConnect.cs Line: 108 

現在,我知道該應用程序的其他功能,因爲如果我要求它將所有晚餐或所有晚餐都大於特定ID或特定晚餐,那麼一切正常,它似乎只是將時間戳與DateTime.Now進行比較。

我知道這很簡單。我究竟做錯了什麼?

+2

sql參數的字符串concatenation是邪惡的。不要這樣做。 – 2010-10-03 00:37:08

回答

5

這句法應該解決您的問題:

NpgsqlCommand sql = db.CreateCommand(); 
sql.CommandType = CommandType.Text; 
sql.CommandText = @"SELECT * FROM dinners WHERE EventDate >= @eventdate ;"; 
sql.Parameters.Add("eventdate", NpgsqlType.Date).Values = DateTime.Now; 

你考慮改變你的查詢(reference),所以這兩個時間戳幾乎是相同的。

+0

謝謝,這讓我足夠接近,弄清楚了。 – andrewheins 2010-10-03 00:30:28

+0

不是值,請使用sql.Parameters.Add(「eventdate」,NpgsqlType.Date).Value = DateTime.Now; – 2017-10-31 06:19:45

5

您正在將命令構建爲字符串,並且不確保DateTime序列化的格式是Postgres將正確解釋的格式。

您可以通過調用DateTime.ToString()並使用適當的格式字符串來使用一致的格式。爲了更加安全,您可以將適當的SQL添加到字符串中,以確保Postgres在讀取命令時明確將其轉換爲日期,而不依賴於隱式轉換。

但是,Npgsql已經有了代碼,可以在每個版本上對其進行NUnit測試。好得多依賴於:

NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM dinners WHERE EventDate >= :date", dinnerConn); 
command.Parameters.Add(":date", DateTime.Now); 

最後一種選擇是不是從.NET傳遞一個DateTime所有,但使用SELECT * FROM dinners WHERE EventDate >= now()。這種方式會在數據庫認爲是當前日期的時候通過。就連接優化而言,有一些次要的優點,但主要原因是爲了保持多個調用者之間的一致性到同一個數據庫中。有一個地方定義了「現在」(在這種情況下是數據庫機器),以防止不同機器的潛在問題略有不同步。

+1

建議現在使用+1()(或者CURRENT_TIMESTAMP)。如果您傳入DateTime.Now並且時區不匹配,並且應用程序和db字段不能同時識別時區,則會得到意想不到的結果。 now()的使用避免了這個問題。 – 2010-10-04 18:44:09