Parse and Format SQL in Java Instantly with JSqlParser

This article introduces JSqlParser, a Java library that parses SQL statements into object structures, demonstrates how to extract query components with sample code, lists supported databases, and highlights additional features like formatting and framework integration.

Programmer DD
Programmer DD
Programmer DD
Parse and Format SQL in Java Instantly with JSqlParser

JSqlParser

JSqlParser is a Java‑written SQL parser that converts SQL statements into Java objects, allowing developers to easily analyze, modify, and refactor queries.

For example, the SQL statement SELECT 1 FROM dual WHERE a = b is parsed into the following object hierarchy:

SQL Text
  └─Statements: net.sf.jsqlparser.statement.select.Select
     └─selectBody: net.sf.jsqlparser.statement.select.PlainSelect
        ├─selectItems → Collection<SelectExpressionItem>
        │  └─selectItems: net.sf.jsqlparser.statement.select.SelectExpressionItem
        │     └─LongValue: 1
        ├─Table: dual
        └─where: net.sf.jsqlparser.expression.operators.relational.EqualsTo
           ├─Column: a
           └─Column: b

Using the provided API, you can access each element of the query:

Statement statement = CCJSqlParserUtil.parse(sqlStr);
if (statement instanceof Select) {
    Select select = (Select) statement;
    PlainSelect plainSelect = (PlainSelect) select.getSelectBody();

    SelectExpressionItem selectExpressionItem =
            (SelectExpressionItem) plainSelect.getSelectItems().get(0);

    Table table = (Table) plainSelect.getFromItem();

    EqualsTo equalsTo = (EqualsTo) plainSelect.getWhere();
    Column a = (Column) equalsTo.getLeftExpression();
    Column b = (Column) equalsTo.getRightExpression();
}

JSqlParser currently supports most major relational databases, including:

Oracle

MS SQL Server and Sybase

PostgreSQL

MySQL and MariaDB

DB2

H2, HSQLDB, and Derby

SQLite

It handles common SQL syntax such as SELECT, INSERT, UPDATE, DELETE, and also offers features like SQL formatting, query generation, and integration with frameworks such as Hibernate and Spring.

Project repository: https://github.com/JSQLParser/JSqlParser

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSQLparsingBackend DevelopmentJSqlParser
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.