2014-04-08 119 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