3

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.

  • Welcome, @Zhang Junlong! Do the answers to [this question](https://stackoverflow.com/questions/10283464/sql-query-where-clause) help you at all? – Martin J.H. Jul 16 '19 at 10:51
  • @MartinJ.H. Thanks, but it doesn't help. I want to manipulate sql query with a Java library -- JSqlParser – Zhang Junlong Jul 17 '19 at 02:19

1 Answers1

3

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
wumpz
  • 8,257
  • 3
  • 30
  • 25
  • Is there a way to add condition to sql without override? – displayname Jun 22 '20 at 08:28
  • Override? You can just replace the where statement. Take the expression it has and add what you want. – wumpz Jun 22 '20 at 12:18
  • You overriding a=1 condition with a=1 and b=2. The question is I want to add new condition to current conditition. Expression hasn't got add function to add new conditions when you get where expression from PlainSelect. [My Question Link](https://stackoverflow.com/questions/62510210/how-to-add-new-condition-with-jsqlparser/62528386#62528386) – displayname Jun 23 '20 at 06:41
  • Create an AndExpression, set left to actual and right to the new condition and then set this using setWhere. – wumpz Jun 23 '20 at 10:38