多条件检索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语句发生错误

 

posted @ 2017-09-14 10:46  蓝色标记  阅读(2683)  评论(0编辑  收藏  举报