目前,我正在尝试检索名为“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'";
但不知何故这不起作用。我没有收到表单卡住并使其无法访问的错误。
这可能是一个很容易解决的问题,但我似乎无法解决。我只显示查询变量的值而不显示其余代码的原因是因为几周来一切都运行良好。
最佳答案
你忘记了括号,你应该使用参数来避免注入(inject)攻击
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);
}
}
关于C# 查询没有被执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29796941/