zoukankan      html  css  js  c++  java
  • <转载>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();//重新加载
            }
        }
    

      

  • 相关阅读:
    简单的远程控制软件
    VS集成环境中的JavaScript脚本语法检查
    vs2022安装
    有关httpContext.Current.Session[值] 取值的问题
    【python3.7】文件操作
    148. 排序链表
    11. 盛最多水的容器
    23. 合并K个升序链表
    147. 对链表进行插入排序
    146. LRU 缓存机制
  • 原文地址:https://www.cnblogs.com/ChangTan/p/2309132.html
Copyright © 2011-2022 走看看