[英]Stored procedure works when executed in query builder, but doesn't work from C# code
[英]C# query doesn't get executed
目前,我正在嘗試檢索名為“ orders”的MySQL數據庫中特定日期之間所有條目的內容。 為此,我使用以下代碼:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and print_location like 'antw'";
dateFrom和dateTill都是包含時間戳的變量。
上面的所有內容都完美運行。 我現在面臨的問題是我要檢查兩個print_locations而不是僅檢查一個。 如上面的代碼所示,我僅搜索“ antw”。 我現在要在兩個print_locations上搜索的代碼如下:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and print_location like 'antw' or print_location like 'helm'";
但是,這不起作用。 我沒有收到錯誤,表格只是凍結而無法訪問。
這可能是一個簡單的問題,但我似乎無法解決。 我之所以只顯示查詢變量的值而不顯示其余代碼的原因,是因為幾周來一切正常。
您忘記了括號,應該使用參數來避免注入攻擊
string Command = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between @dateFrom and @dateTill and (print_location like 'antw' or print_location like 'helm')";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("@dateFrom", yourDateFrom));
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("@dateTill", yourdateTill));
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
}
}
在您的邏輯中添加方括號:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and (print_location like 'antw' or print_location like 'helm')";
但是要小心...這聞起來像是潛在的SQL注入情況!
從來沒有使用過MySQL,但是也許您忘記了LIKE
子句中的%%。 這樣,它將像=
一樣工作。
SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and (print_location like '%antw%' or print_location like '%helm%')
您需要在條件的第二組“或”上加上括號:
query =“ SELECT id,日期,contactinfo,orderinfo,內容,print_location,order_id,file_size FROM訂單,其中日期介於” + dateFrom +“和” + dateTill +“之間,並且(print_location如'antw'或print_location如'helm')” ;
否則,您的語句將如下所示:
給我所有這些東西,日期在此日期和該日期之間,以及print_location之類的“ antw” ...
或者讓我把所有這些東西都帶到print_location之類的“ helm”。
由於您使用的是點贊,因此執行查詢時可能只是凍結了。 它最終將完成,並且您將獲得比預期更多的結果。
另外,由於注入問題和數據建模,您實際上應該使用數據訪問對象模型(DAO)。 我建議研究一下!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.