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.
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: bUsing 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
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
