<转载>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/archive/2011/12/31/2309132.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值