0

在我的网络应用程序中,我有一个搜索框,以便我可以使用名字或姓氏搜索我的数据库,它将在我的网络应用程序中显示结果。用户输入名字或姓氏。使用 Like 查询..如何编写 Like 查询这个查询。

 public DataTable SearchbyOPDname(string fname, string lname)
   {
       if (con.State == ConnectionState.Closed)
       {
           con.Open();
       }
       string sql = "SELECT opd_id AS [OPD No], opd_date AS DATE, opd_dpt AS DEPARTMENT, 
       opd_pfname AS [FIRST NAME], opd_plname AS [LAST NAME], opd_age AS AGE, opd_gender AS GENDER, 
       opd_mob AS [MOBILE NO], opd_fthrname AS [FATHER NAME], opd_hsbndname AS [HUSBAND NAME] 
       FROM tbl_OPD WHERE opd_pfname like'" + fname +"' OR opd_plname like'" + lname + "'ORDER BY DATE DESC";
       SqlDataAdapter adp = new SqlDataAdapter(sql, con);
       DataTable dt = new DataTable();
       adp.Fill(dt);
       con.Close();
       return dt;
   }
4

2 回答 2

1

我认为你需要%为你所用LIKE

WHERE opd_pfname LIKE '%" + fname + @"%' OR opd_plname LIKE '%" + lname + @"%'

但更重要的是(正如我在评论中提到的)始终使用参数化查询您的代码对SQL 注入攻击是开放的。例如;

         WHERE opd_pfname LIKE '%' + @fname + '%'
            OR opd_plname LIKE '%' + @lname + '%'

cmd.Parameters.AddWithValue(@fname, fname);
cmd.Parameters.AddWithValue(@lname, lname);

SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
于 2013-03-19T14:47:20.640 回答
0

如果您想使用 LIKE 进行部分匹配,则必须%在模式之前和之后包含符号。这应该可以正常工作:

string sql = @"SELECT opd_id AS [OPD No]
              , opd_date AS DATE
              , opd_dpt AS DEPARTMENT
              , opd_pfname AS [FIRST NAME]
              , opd_plname AS [LAST NAME]
              , opd_age AS AGE
              , opd_gender AS GENDER
              , opd_mob AS [MOBILE NO]
              , opd_fthrname AS [FATHER NAME]
              , opd_hsbndname AS [HUSBAND NAME] 
          FROM tbl_OPD 
         WHERE opd_pfname LIKE '%" + fname + @"%'
            OR opd_plname LIKE '%" + lname + @"%'
         ORDER BY DATE DESC";

作为旁注,您应该使用参数化查询,而不是像那样手动构建查询!

以下是如何对参数化查询执行相同操作:

  using(SqlCommand cmd = con.CreateCommand())
  {
     cmd.Text = @"SELECT opd_id AS [OPD No]
              , opd_date AS DATE
              , opd_dpt AS DEPARTMENT
              , opd_pfname AS [FIRST NAME]
              , opd_plname AS [LAST NAME]
              , opd_age AS AGE
              , opd_gender AS GENDER
              , opd_mob AS [MOBILE NO]
              , opd_fthrname AS [FATHER NAME]
              , opd_hsbndname AS [HUSBAND NAME] 
          FROM tbl_OPD 
         WHERE opd_pfname LIKE '%' + @fname + '%'
            OR opd_plname LIKE '%' + @lname + '%'
         ORDER BY DATE DESC"

     cmd.Parameters.AddWithValue(@fname, fname);
     cmd.Parameters.AddWithValue(@lname, lname);

     cmd.Prepare();

     SqlDataAdapter adp = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     adp.Fill(dt);
  }
   con.Close();
于 2013-03-19T14:45:43.670 回答