<转载>C# 中参数化模糊查询

这是我觉得非常有必要记录的一个知识点,今天尝试过N次,都没有搞定。最后在网上搜了下终于明白了ASP.Net之参数化模糊查询参数化的奥妙。

首先是sql语句组织一块

例如:string sql = "select * from tb_Student where Name like @Name"; 我就是在这里弄了很久 不知道%要插在什么地方。

其次是参数的构造:

SqlCommand comm = new SqlCommand(sql, con);

comm.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = "%" +this.TextBox1.Text.Trim()+ "%";//把文本框里的值赋给@Name

关键就是: "%" +this.TextBox1.Text.Trim()+ "%";在把值赋给参数之前加上百分号

下面来个小例子:

     /// <summary>
    /// 模糊查询
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (this.TextBox1.Text != "")//判断是否为空
        {
            SqlConnection con = GetConnection();
            con.Open();//打开连接

            //使用command对象查询数据库中的记录
            string sql = "select * from tb_Student where Name like @Name";
            SqlCommand comm = new SqlCommand(sql, con);
            comm.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = "%" +this.TextBox1.Text.Trim()+ "%";//把文本框里的值赋给@Name 用到了模糊查询
            SqlDataAdapter adapter = new SqlDataAdapter(comm);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            //判断表中是否有数据
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridView1.DataSource = ds;//如果有就显示出来
                GridView1.DataBind();
            }
            else
            {
                Response.Write("<script>alert('没有相关记录')</script>");
            }
            //释放资源 关闭连接
            adapter.Dispose();
            ds.Dispose();
            con.Close();
        }
        else
        {
            this.bind();//重新加载
        }
    }

  

原文地址:https://www.cnblogs.com/ChangTan/p/2309132.html