记-SQL语法校验、格式化

唐炜
2023-12-01

1.pom.xml

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>

2.示例代码

    @org.junit.Test
    public void test() {
        String sql = "SELECT ID,NAME FROM USER WHERE DEL = '0' ORDER BY CREATE_TIME";
        final DbType dbType = JdbcConstants.MYSQL;
        List<SQLStatement> statementList = SQLUtils.parseStatements(sql, dbType);
        final String format = SQLUtils.format(sql, dbType, SQLUtils.DEFAULT_FORMAT_OPTION);
        System.out.println(format);
        System.out.println("=====================================================");
        for (SQLStatement statement : statementList) {
            if (statement instanceof SQLSelectStatement) {
                final SQLSelectStatement selectStatement = (SQLSelectStatement) statement;
                final SQLSelect select = selectStatement.getSelect();
                // UNION查询取第一个Select子句
                final SQLSelectQueryBlock queryBlock = select.getFirstQueryBlock();
                System.out.println("查询列:" + queryBlock.getSelectList());
                System.out.println("表名:" + queryBlock.getFrom());
                System.out.println("查询条件:" + queryBlock.getWhere());
            }
        }
    }

参考:

Druid SqlParser理解及使用入门
SQL-Parser

 类似资料: