mysql选择Like列,如column1或column2

时间:2013-03-19 14:41:17

标签: c# mysql

在我的webapp中,我有一个搜索框,以便我可以使用firstname或lastname搜索我的数据库,它将在我的web app中显示结果。用户输入firstname或lastname.Use like query..how to write就像在这个查询中的查询一样。

 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;
   }

2 个答案:

答案 0 :(得分:1)

我认为您需要%部分使用LIKE;

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

但更重要的是(正如我在comment中提到的)始终使用 parameterized queries 。您的代码是针对 SQL Injection 攻击开放的。例如;

         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);

答案 1 :(得分: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();