2010-10-03 65 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