8

Does anyone know about a SQL statements parser, in Java, that would allow having an Object representation of a SQL query, allow modifying this representation and generate back the updated SQL statement?

Regards, Christophe

3
  • 3
    Out of curiosity : why would you want to do this? We might suggest alternatives. Commented Aug 20, 2010 at 12:31
  • I support @Peter Tillemans question. Maybe there's a way to create the object tree representation before hand, do whatever you want and only translate it to SQL as a final export for execute. Commented Aug 20, 2010 at 12:33
  • I'm working at the JDBC driver level (and I want to) to catch SQL statements sent by my application but I'd like to rewrite these statements partially (modify some table names for instance). Commented Aug 22, 2010 at 5:31

3 Answers 3

2

I would think that ANTLR would be able to do this.

Sign up to request clarification or add additional context in comments.

3 Comments

I think so, but I was looking for a, let's say, simpler solution. With ANTLR, I still need to generate the parser on my own and actually, I did not find the information if the SQL ANSI grammar was compatible with the ANTLR v3. Not sure either that you can update the model and generate back the SQL string.
I'm not deeply familiar with ANTLR. I'm pretty sure you can update the model. Regenerating the SQL string should be at worst straightforward tree walk-and-print, and ANTLR has something called "string templates" to help. Yes, you're likely to have do some work to get your result if you use ANTLR. You should ask at the ANTLR site.
Some late feedback... ANTLR is definitely is solution for that. I used the SQL grammar along with ANTLR v2. I modified the grammar to record the tokens holding "table" ASTNode and changed their values.
0

Maybe you could look at JSqlParser.

1 Comment

I found that one as well. It is not very clear if you can change the SQL model and get back the rewritten SQL. Maybe to toString() will do the job.
0

This is a demo use Java SQL Parser do something like this:

Input SQL:

SELECT A as A_Alias, B AS B_Alias FROM TABLE_X

If you need to remove the second column “B AS B_Alias” from the select list, just do something like this:

columns.removeResultColumn(1); // 0 is the first column

then you will get this new SQL(the , was removed automatically):

SELECT A as A_Alias FROM TABLE_X

this demo also illustrates how to replace a column, Add criteria (where clause), Add Order by clause and etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.