0

I'm using JsqlParser 0.8.0.

I have the following string:

String sql = "SELECT table alias FROM table;";

CCJSqlParserManager pm = new CCJSqlParserManager();

Select s = (Select) pm.parse(new StringReader(sql));

System.out.println(s.getSelectBody());

I expected the table AS alias to be printed, but the whole sql-query was printed instead. How can I make printing only the SelectBody.

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 1
    the selectbody will only tell you what type of query it is (eg instanceof update, select , delete, insert) you didn't actually run the query so your alias hasn't been added to the table name, check this out for how it's used http://www.programcreek.com/java-api-examples/index.php?api=net.sf.jsqlparser.parser.CCJSqlParserManager – Jeremy C. May 22 '15 at 08:02

1 Answers1

1

SelectBody is of type PlainSelect. This is not equivalent to the SelectItems which you want to get. This is an example for getting these items:

String sqlStr = "SELECT mytable alias FROM mytable";
Select select = (Select)CCJSqlParserUtil.parse(sqlStr);
System.out.println(select.getSelectBody());

PlainSelect pl = (PlainSelect)select.getSelectBody();
for (SelectItem item : pl.getSelectItems()) {
    System.out.println(item.toString());
}

By the way this example is using JSqlParser V0.9.3 but the relevant parts of getting the SelectItems are identical in V0.8.0.

You should not using keywords as column or tablenames. This could confuse in many ways the parsing process. However, more and more keywords are allowed in recent versions of JSqlParser.

wumpz
  • 8,257
  • 3
  • 30
  • 25