2014-04-08 123 views
0

我需要从当前日期减去30天然后我筛选查询,但我没有得到任何结果/输出,为什么什么我的这个代码错误,如果我运行此代码只c#中的错误从当前日期减去30天?的WinForms

DateTime curdate = DateTime.Now; 
curdate = curdate.AddDays(-30); // if i give -4 instead of -30 the query will bind data 
DateTime curdate1 = DateTime.Now; 

validateDept.InitializeConnection(); 
OleDbConnection connection = new OleDbConnection(validateDept.connetionString); 
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT InvoiceId, InvoiceNumber, InvoiceDate, (Select CustomerId from Customer Where Customer.CustomerId=NewInvoice_1.CustomerName) AS CustomerId, (Select CustomerName from Customer where Customer.CustomerId = NewInvoice_1.CustomerName) AS CustomerName, DueDate, Tax, GrandTotal, CompanyId FROM NewInvoice_1 WHERE InvoiceDate >= '" + curdate + "' AND InvoiceDate <= '" + curdate1 + "' ", connection); 
DataSet sourceDataSet = new DataSet(); 
adapter.Fill(sourceDataSet); 
gridControl1.DataSource = sourceDataSet.Tables[0]; 

空表所示。如果我将-30更改为-4,则它将从Access DB中读取一行。从4月4日到现在的日期4月8日如果我们给-3,-4,-5,-6,-7这段代码但工作很小的错误是“<”&“>”这只能工作“=”标志不工作这个代码?

非常感谢。

+3

与参数的工作原理错误的是它到一个字符串,它取决于日期的格式...和服务器的格式,也读了关于SQL注入,所以你没有通过一个日期,你传递一个stng,这是为什么不工作 –

+1

在除了@Mr。 - 有关示例,请参见[OleDbParameter](http://msdn.microsoft.com/library/system.data.oledb.oledbparameter.aspx)。 – Corak

+0

@Mr。 - 如果参数是一个日期,这将是很难做SQL注入 - 但仍然同意参数是在这里做的正确的事情 – Greg

回答

0

,如果你使用的是访问数据库,然后使用#不“” 一件事传递日期字符串月份的全称是因为你正在转换会忽略当地的日期设置

DateTime curdate = DateTime.Now; 
curdate = curdate.AddDays(-30); // if i give -4 instead of -30 the query will bind data 
DateTime curdate1 = DateTime.Now; 

validateDept.InitializeConnection(); 
OleDbConnection connection = new OleDbConnection(validateDept.connetionString); 
OleDbDataAdapter adapter = new OleDbDataAdapter(
     "SELECT InvoiceId, InvoiceNumber, InvoiceDate, (Select CustomerId from Customer 
     Where Customer.CustomerId=NewInvoice_1.CustomerName) AS CustomerId, (Select 
     CustomerName from Customer where Customer.CustomerId = NewInvoice_1.CustomerName) 
     AS CustomerName, DueDate, Tax, GrandTotal, CompanyId FROM NewInvoice_1 WHERE 
     InvoiceDate >= #" + curdate.ToString("dd/MMM/yyyy") + "# AND InvoiceDate <= #" +   
     curdate1.ToString("dd/MMM/yyyy") + "# ", connection); 

DataSet sourceDataSet = new DataSet(); 
adapter.Fill(sourceDataSet); 
gridControl1.DataSource = sourceDataSet.Tables[0]; 
+0

Hi @jack,感谢您的回答,但仍面临同样的问题:( – Sri