首页 > 解决方案 > 解析 SQL 查询字符串以获取值的映射

问题描述

我有一个 java 项目,其中 PreparedStatements 没有在任何 SQL 查询中使用。现在我想为所有这些查询实现 PreparedStatements。而不是通过放置“?”来修改每个查询 ,我想写一个函数,它接受 SQL 查询字符串,它解析它并返回各种 SQL 子句的值的映射。

public class SQLParser {

    public static void main(String args[]) {

    String sqlString = "select * from table t where columnA = 'hello' and columnB = 'hai'";
    Map<Integer,String> values = new HashMap<>();
    values = parseQuery(sqlString);
    System.out.println(values);   // prints  { {1,'hello'} , {2,'hai'} }
    }

    private static Map<Integer,String> parseQuery(String sqlString) {
        Map<Integer,String> values = new HashMap<>();
        //
        //  ????  I want this function 
        //
        return values;
        
    }

}

几个例子是

sqlString : select * from table t where columnA = 'hello' AND columnB = 'hai'
输出: { {1,'hello'} , {2,'hai'} }

sqlString : select * from table t where columnA IN ('hello' ,'hai')
output : { {1,'hello'} , {2,'hai'} }

sqlString : select * from table t where columnA > 17 AND columnB BETWEEN 10 AND 20;
输出:{ {1,'17'} , {2, '10' } , {3, '20'} }

基本上它应该支持所有可能的子句及其组合。

标签: javasqlsql-parser

解决方案


实现它的正确方法是创建 SQL 解析器。这是一项艰巨的任务。如果您决定采用这种方式,您可以查看我的解析器(Scala),但它甚至还没有接近完成。

另一种方法是创建正则表达式来捕获所有文字。您只需要扫描仪,这更容易。


推荐阅读