多条件组合查询Sql语句巧用StringBuffer
来源:互联网 发布:灯光演播室软件 编辑:程序博客网 时间:2024/06/18 02:04
StringBuffer的使用:
线程安全的可变字符序列。一个类似于 String的字符串缓冲区,但不能修改。虽然在任意时间点上它都包含某种特定的字符序列,但通过某些方法调用可以改变该序列的长度和内容。
可将字符串缓冲区安全地用于多个线程。可以在必要时对这些方法进行同步,因此任意特定实例上的所有操作就好像是以串行顺序发生的,该顺序与所涉及的每个线程进行的方法调用顺序一致。
StringBuffer上的主要操作是 append
和 insert
方法,可重载这些方法,以接受任意类型的数据。每个方法都能有效地将给定的数据转换成字符串,然后将该字符串的字符添加或插入到字符串缓冲区中。append
方法始终将这些字符添加到缓冲区的末端;而insert
方法则在指定的点添加字符。
在写sql语句时,先把各个条件加进去,然后对StringBuffer修改
先举一个简单的例子:
import java.util.Scanner;public class TestStringBuffer {public static void main(String[] args) {StringBuffer sb=new StringBuffer("select * from tcmjkc where");Scanner scan=new Scanner(System.in);int i=scan.nextInt();int j=scan.nextInt();if(i>0){sb.append(" and helloii");}else{sb.append(" and byebyeii");}if(j>0){sb.append(" and hellojj");}else{sb.append(" and byebyejj");}System.out.println(sb.toString().replaceFirst(" and", ""));//判定之后先把各个条件加进去,然后对StringBuffer修改//把第一个" and"去掉,注意and前面有一个空格//注意书写sql语句时,要严格注意格式,空格、单引号、双引号等}}输出结果:
1 1select * from tcmjkc where helloii and hellojj
在做组合查询时,可能会用到多个控件,这里以JRadioButton举例:
//model组合查询//传入JRadioButton是否被选中,如果选中,就加入条件//先放入where,最后去掉第一个 " and"public ResultSet modelsearch(Connection con,Model model,JRadioButton fl_radioButton,JRadioButton hd_radioButton,JRadioButton kd_radioButton,JRadioButton kcsl_radioButton) throws Exception{StringBuffer sb=new StringBuffer("select * from tcmjkc where");PreparedStatement pstmt = null;if(fl_radioButton.isSelected()){sb.append(" and 分类 like'%"+model.getFl()+"%'");}if(hd_radioButton.isSelected()){sb.append(" and 厚度 like'%"+model.getHd()+"%'");}if(kd_radioButton.isSelected()){sb.append(" and 宽度 like'%"+model.getKd()+"%'");}if(kcsl_radioButton.isSelected()){sb.append(" and 库存数量 = "+model.getKcsl());}if(!fl_radioButton.isSelected()&&!hd_radioButton.isSelected()&&!kd_radioButton.isSelected()&&!kcsl_radioButton.isSelected()){//如果都没有选中,就去掉where//20.26sb.delete(20, 26);}else{ pstmt=con.prepareStatement(sb.toString().replaceFirst(" and", ""));}return pstmt.executeQuery();}
0 0
- 多条件组合查询Sql语句巧用StringBuffer
- 多条件组合查询,sql语句连接
- 多条件查询SQL语句
- SQL多条件查询语句
- 多条件查询SQL语句
- sql多条件查询语句
- sql语句多条件查询
- 多项查询条件组合下的SQL语句生成
- 多条件组合查询SQL优化一则
- linq to sql 多条件组合查询
- 多条件组合查询,并根据指定类别找出所有最小子类别的SQL语句备忘
- SQL多条件查询Sql语句
- sql查询条件语句
- 关于多条件查询的SQL语句
- 实现多条件模糊查询SQL语句
- SQL的多条件查询语句
- 实现多条件模糊查询SQL语句
- 构建Sql多条件查询语句
- 设计模式-装饰者模式(Decorator)
- iOS中的高精度图片采集和使用注意点和关键步骤
- .Net web service studio的使用
- 安卓开源项目周报0405
- 关于stimusoftreports 报表打印预览时多出一空白页问题记录
- 多条件组合查询Sql语句巧用StringBuffer
- 使用swig包装C或C++源代码在windows下用命令行编译并用distutils打包供python使用
- 江苏科技大学“FlySpiders"本创小组成立
- 高通Android平台下关于display部分的几个关键问题
- Java EE 开发中遇到String can not be resolved to a type
- error C2872: “ACCESS_MASK”: 不明确的符号
- Wildfly使用时的问题
- 杭电oj-Climbing Worm
- 树模型(1)-入门指南