java - 解析 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'} }
基本上它应该支持所有可能的子句及其组合。
解决方案
实现它的正确方法是创建 SQL 解析器。这是一项艰巨的任务。如果您决定采用这种方式,您可以查看我的解析器(Scala),但它甚至还没有接近完成。
另一种方法是创建正则表达式来捕获所有文字。您只需要扫描仪,这更容易。
推荐阅读
- python - 如何在 Django 中使用 ListView 不显示任何记录?
- android - 如何在没有 Visual Studio 的情况下下载 Android SDK?
- azure-machine-learning-studio - 通过 REST 调用在 Azure ML Studio 中执行以下操作
- list - 从飞镖列表中删除重复项目时出现问题
- java - Java spring 上的单独事务
- javascript - 承诺 {
.forEach 不是函数 - android - 当iOS应用程序在后台时,android设备可以检测到充当外围设备的iOS设备吗?
- c# - 将每个 id 的数据合并到一行并删除重复项
- c# - 如何将自定义属性添加到 asp.net 下拉列表
- java - 如何在从服务引发异常的休息控制器中模拟异常