zoukankan      html  css  js  c++  java
  • 【java/正则表达式】用正则表达式解决查询语句条件输入不完全而整句SQL无需修改的问题

    需求:

    界面上有四个输入框,分别对应查询语句的四个参数,查询语句是:

    select * from a=:av and b=:bv and c=:cv and d = : dv

    当输入框没有用户输入时,该项条件即不存在,比如bv没有输入,那么真实的sql应该是

    select * from a=:av and c=:cv and d = : dv 或与之等价的SQL

    如select * from a=:av and 1=1 and c=:cv and d = : dv

    当四个都不输入时,最终sql便是select * from a或是与之等价的SQL。

    换而言之,select * from a=:av and b=:bv and c=:cv and d = : dv 写成后,用户并不希望修改它或是写多份备用,而是希望程序通过输入参数而动态调整SQL。

    思索:

    用正则表达式知道条件对应的模式,如果输入了就将值部分替换为真实数,没有输入就把该项变成1=1.

    比如用户指定av=1,cv=3,dv=4,bv没有输入,那么最终的SQL是:

    select * from a=1 and 1=1 and c=3 and d = 4

    实现:

    import java.util.HashMap;
    import java.util.Map;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Test {
        public static void main(String[] args) {
            String rawSql="select * from a=:av and b=:bv and c=:cv and d = : dv";
            System.out.println("rawSql="+rawSql);
            
            // 模拟输入的条件
            Map<String,String> map=new HashMap<>();
            map.put("av", "1");
            //map.put("bv", "2");// 被屏蔽的表示此条件未输入
            map.put("cv", "3");
            map.put("dv", "4");
            
            Pattern pattern=Pattern.compile("((\w+)\s*[=]\s*)([:]\s*(\w+))");
            Matcher matcher=pattern.matcher(rawSql);
            boolean found=matcher.find();
            
            StringBuilder sb=new StringBuilder();
            while(found) {
                String value=matcher.group(4);
                
                if(map.containsKey(value)) {
                    matcher.appendReplacement(sb, matcher.group(1)+map.get(value));
                }else {
                    matcher.appendReplacement(sb, "1=1");
                }
                
                found=matcher.find();
            }
            matcher.appendTail(sb);
            
            String finalSql=sb.toString();
            System.out.println("finalSql="+finalSql);
        }
    }

    输出:

    rawSql=select * from a=:av and b=:bv and c=:cv and d = : dv
    finalSql=select * from a=1 and 1=1 and c=3 and d = 4

    -END-

  • 相关阅读:
    Python 面向对象3-类变量与实例变量
    Python面向对象2-类和构造方法
    Linux LVM动态扩容
    Anslib 使用错误归纳
    Linux Centos7安装最新anslib
    Linux 配置最新的epel源
    Linux centos7安装python3并且不影响python2
    docker compose启动服务超时重启记录
    spring cloud学习(三)使用Ribbon实现客户端负载均衡
    spring cloud 学习(二)关于 Eureka 的学习笔记
  • 原文地址:https://www.cnblogs.com/heyang78/p/15327315.html
Copyright © 2011-2022 走看看