c#
2014-01-22 191 views 1 likes 
1
DateTime fromDate = dateTimePicker1.Value, toDate = dateTimePicker2.Value; 

string query2 = "select * from Sales where DatePurchased >= '" + fromDate.ToShortDateString() + "' AND DatePurchased <='" + toDate.ToShortDateString() + "'"; 

using (OleDbConnection conn2 = new OleDbConnection(connStr)) 
{ 
    using (OleDbCommand command = new OleDbCommand(query2, conn2)) 
    { 
     command.Connection = conn2; 
     conn2.Open(); 
     OleDbDataReader reader = command.ExecuteReader(); 

     while (reader.Read()) 
     { 
      graphics.DrawString(string.Format("{0:000000}", reader.GetInt32(0)), font, new SolidBrush(Color.Black), startX, startY + offset); 
      graphics.DrawString(reader.GetString(1), font, new SolidBrush(Color.Black), startX+90, startY + offset); 
      graphics.DrawString(reader.GetString(2), font, new SolidBrush(Color.Black), startX + 250, startY + offset); 
      graphics.DrawString(Convert.ToString(reader.GetDouble(3)), font, new SolidBrush(Color.Black), startX + 500, startY + offset); 

      startY += 35; 
     } 
    } 
} 

我在這裏歌廳的錯誤:查詢過濾數據庫

OleDbDataReader reader = command.ExecuteReader(); 

錯誤

「OleDbException是未處理:條件表達式中數據類型不匹配。」

我不知道該怎麼辦,我的數據庫中的數據是日期/時間。請幫助

+0

前工作,我把一個'breakpoint'本着'串QUERY2 = 「SELECT * FROM銷售,其中購置日期> =「」 + fromDate.ToShortDateString() +「'AND DatePurchased <='」+ toDate.ToShortDateString()+「'」;'看看'query2'是什麼? –

+0

抱歉,但我不知道如何放置斷點。你能教我如何? – user3221836

+0

檢查日期格式...什麼是「fromDate」和「toDate」是YYYY-MM-DD而不是ToShortDateString() –

回答

1

你ToShortDateString()不是SQL兼容的字符串:

fromDate.ToString("yyyyMMdd") 

會給你一個SQL兼容的日期字符串。

string query2 = "select * from Sales where DatePurchased >= '" + fromDate.ToString("yyyyMMdd")+ "' AND DatePurchased <='" + toDate.ToString("yyyyMMdd")+ "'"; 

然而,它會更好地使用參數化查詢。

+0

它不起作用 – user3221836

+0

我如何使用參數化查詢? – user3221836

+1

用於參數化查詢請參閱 - > http://www.codeproject.com/Tips/231217/Parameters-SqlCommand-vs-OledbCommand-and-OdbcComm –

0

如果你的固定誤差試着改變你的查詢作爲

string query2 = "select * from Sales where DatePurchased between " + fromDate.ToShortDateString() + " AND " + toDate.ToShortDateString() + " " 

如果它不能正常工作,請檢查您是否有這兩個日期範圍的數據。

0

試試這個:

string query2 = "select * from Sales where DatePurchased >= '" + fromDate.ToString("yyyy-MM-dd") + "' AND DatePurchased <='" + toDate.ToString("yyyy-MM-dd") + "'"; 

相關問題