zoukankan      html  css  js  c++  java
  • 多条件检索SQL语句的拼接

    需求分析 :  

     在使用多条件查询的时候,比如这样的一个图书查询页面:

    如果使用sql语句: select * from book where bookname='name' and author='author' and address='address‘

    但是,在不知道哪一栏会被输入进去,where和and 的使用,有点不知所错,当然,也可以把所有可能的情况所使用的SQL语句一个一个的逻辑判断,

    显然,这样子是很不合适的,这时候,就需要对sql语句的拼接。

                string sql = "select * from Book";
                StringBuilder sb = new StringBuilder();
                sb.Append(sql);
                List<string> wheres = new List<string>();
                List<SqlParameter> parma = new List<SqlParameter>();
    
                if (textBox1.Text.Length > 0)
                {
                    wheres.Add(" bookname  like @name ");
                    //赋值,要使用到模糊查询,%号的添加技巧
                    parma.Add(new SqlParameter("@name", "%" + textBox1.Text + "%"));
    
                }
                if (textBox2.Text.Length > 0)
                {
                    wheres.Add(" bookauthor like @author ");
                    parma.Add(new SqlParameter("@author","%"+textBox2.Text+"%"));
                }
                if (textBox3.Text.Length > 0)
                {
                    wheres.Add(" bookaddress like @address ");
                    parma.Add(new SqlParameter("@address", "%" + textBox3.Text + "%"));
                }
                //有一个条件,就添加where,然后多条件就在中间加and
                if (wheres.Count > 0)
                {
                    sb.Append(" where ");
                    sb.Append(string.Join(" and ", wheres.ToArray()));
                }    

    结:  使用到list集合,以及字符串处理的插入 。需要注意的是,list集合中的sql条件语句 要多加一个或者两个空格,避免把 where或者and插入的时候,两个字符串粘在一起,导致sql语句发生错误

  • 相关阅读:
    EFI下WIN8.1和Ubuntu的双系统安装
    硬盘损坏,全盘数据没了,杯具
    GEC2440的RTC时钟
    纠正一下apache2服务器的搭建
    qt和html的比较
    dump做个备份,发个随笔记录下
    忙了1天的qte-arm环境的搭建
    内核版本不同导致无法加载驱动
    wayne生产环境部署(360的容器发布平台-开源)
    openstack swift curl 常用操作
  • 原文地址:https://www.cnblogs.com/xsh-cs/p/7519492.html
Copyright © 2011-2022 走看看