JSqlParser

What is it

JSqlParser parses an SQL statement and translate it into a hierarchy of Java classes.
The generated hierarchy can be navigated using the Visitor Pattern


How it works

It is built using JavaCC. The core JavaCC grammar for SQL has been taken from Guido Draheim's site and has been changed in order to produce a hierarchy of Java classes.


Alternatives to JSqlParser?

General SQL Parser looks pretty good, with extended SQL syntax (like PL/SQL and T-SQL) and java + .NET APIs. The tool is commercial (license available online), with a free download option.


How it can be used

The method CCJSqlParserManager.parse returns a class implementing Statement which can be used to navigate the structure representing the SQL statement.
To avoid using the instanceof operator as in:

                  
        if (statement instanceof Insert) {
           // insert case
        }
        else if (statement instanceof Update) {
           // update case
        }
                     

the hierarchy can be accessed using proper visitors:

                  
        void visit(Insert statement) {
           // insert case
        }
	
        void visit(Update statement) {
           // update case
        }