3

我有一个非常奇怪的问题,我不知道如何解决这个问题。

我对我的项目有一个预先搜索,基本上是学校搜索

我的问题是我LIKE用来比较选项,在搜索结束时,我的查询应该如下所示:

select *
from tbl_schooldetails
where
  state = 'Gujarat'
  and city = 'Ahmedabad'
  and area = 'Navrangpura'
  and ( board = 'xx' or board LIKE '%CBSE Board%' or board LIKE '%Gujarat Board%')

但相反,我得到以下查询:

select *
from tbl_schooldetails
where
  state = 'Gujarat'
  and city = 'Ahmedabad'
  and area = 'Navrangpura'
  and ( board = 'xx' or board LIKE '�SE Board%' or board LIKE '%Gujarat Board%')

如果您注意到我%CB的已转换为“ �”符号,因此我无法搜索与“CBSE Board”选项相关的任何结果。

谁能告诉我如何摆脱这种 URL 编码?

这是我生成此查询的代码:

  string qry = "select * from tbl_schooldetails where state = '" + sdpd4.SelectedItem.Text + "'";

    if (sdpd2.SelectedItem.Text != "Select City")
    {
        qry += " and city = '" + sdpd2.SelectedItem.Text + "'";
    }

    if (sdpd1.SelectedItem.Text != "Select Area")
    {
        qry += " and area = '" + sdpd1.SelectedItem.Text + "'";
    }

    if (CheckBoxList3.SelectedItem != null)
    {
        qry = qry + " and ( board = 'xx'";

          for (int i = CheckBoxList3.Items.Count - 1; i >= 0; i--)
          {
              if (CheckBoxList3.Items[i].Selected == true)
              {

                  string mt = CheckBoxList3.Items[i].ToString();
                  qry = qry + " or board LIKE '" + '%' + mt + '%' + "'";

              }
          }
            qry = qry + ")";
    }


    if (RadioButtonList1.SelectedItem != null)
    {
        qry += " and gender ='" + RadioButtonList1.SelectedItem.Text + "'";
    }



    Response.Redirect("schoolsearchresult2.aspx?search=" + qry);
4

2 回答 2

4

现在编辑,原来的问题更清楚了。

只需更改此:

Response.Redirect("schoolsearchresult2.aspx?search=" + qry);

对此:

Response.Redirect("schoolsearchresult2.aspx?search=" 
    + HttpServerUtility.UrlEncode(qry));

...但是:我的警告(以及其他所有人的警告)仍然正确:在查询字符串中传递 WHERE 子句是非常危险的——对结果 URL 的微不足道的调整可能会破坏您的数据库。

原始答案

您似乎将 %CB 放入 URL 中,该 URL 在服务器上被解释为十六进制数字。

如果您使用 %25CB,则应将其解释为“%CB”。

或者,您可以使用内置的 c# 函数之一。我认为您需要的是HttpServerUtility.UrlEncode

很重要:

如果这是一个真正的应用程序,而不是一个概念验证项目,那么您不能直接将数据从 URL 复制到您的 SQL 字符串中!

于 2012-07-26T21:46:15.077 回答
0

我建议您以这种方式构建您的 sql 查询,这样您就不必担心 url 编码和 Sql Injection

string sqlQuery = "select *
from tbl_schooldetails
where
  state = @state
  and city = @city
  and area = @area
  and ( board = @board1 or board LIKE ";
 sqlQuery += "%@board2%";
sqlQuery += " or board LIKE %@board3%");

然后在执行查询时使用

例如

SqlCommand cmd = new SqlCommand(command);
cmd.Parameters.AddWithValue("@state", Request.Form["state"]);

...... 等等

于 2012-07-26T21:55:53.377 回答