How to add where condition to sql with JSqlParser?

六月ゝ 毕业季﹏ 提交于 2021-02-10 06:32:34

问题


I want to add where condition to sql with JSqlParser, for example:

Before:

select * from test_table where a=1 group by c

After:

select * from test_table where a=1 and b=2 group by c

However, I cannot find any example codes.


回答1:


One solution would be:

String sql = "select * from test_table where a=1 group by c";
Select select = (Select) CCJSqlParserUtil.parse(sql);
Expression where = CCJSqlParserUtil.parseCondExpression("a=1 and b=2");
((PlainSelect) select.getSelectBody()).setWhere(where);
System.out.println(select.toString());

First, you have to parse the existing SQL. Using this PlainSelect cast you are getting access to the where clause of your statement, at least at the object it holds it.

The where expression is generated using the convenience method CCJSqlParserUtil.parseCondExpression.

The output of those statements is:

SELECT * FROM test_table WHERE a = 1 AND b = 2 GROUP BY c


来源:https://stackoverflow.com/questions/57055443/how-to-add-where-condition-to-sql-with-jsqlparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!