jsqlparser或druid解析SQL语句

1.使用jsqlparser解析

  1. 引入jsqlparser包:
<!--jsqlparser-->
<dependency>
    <groupId>com.github.jsqlparser</groupId>
    <artifactId>jsqlparser</artifactId>
    <version>4.6</version>
</dependency>
  1. 使用工具类解析
/**
 * SQL语句解析
 *
 * @param sql 原SQL
 * @return select:[table1,table2]
 */
public static Map<String, Object> sqlParser(String sql) {
    Map<String, Object> result = new HashMap<>();
    if (StringUtils.isEmpty(sql)) {
        return result;
    }
    try {
        String operation = "";
        Set<String> tableList = new HashSet<>();
        Statement statement = CCJSqlParserUtil.parse(new StringReader(sql));
        if (statement instanceof Select) {
            operation = "SELECT";
            Select select = (Select) statement;
        } else if (statement instanceof Delete) {
            operation = "DELETE";
            Delete delete = (Delete) statement;
            Table table = delete.getTable();
            String tableName = table.getName();
            tableList.add(tableName);
        } else if (statement instanceof Update) {
            operation = "UPDATE";
            Update update = (Update) statement;
            Table table = update.getTable();
            String tableName = table.getName();
            tableList.add(tableName);
        } else if (statement instanceof Insert) {
            operation = "INSERT";
            Insert insert = (Insert) statement;
            Table table = insert.getTable();
            String tableName = table.getName();
            tableList.add(tableName);
        } else if (statement instanceof Merge) {
            operation = "Merge";
            Merge merge = (Merge) statement;
            Table table = merge.getTable();
            String tableName = table.getName();
            tableList.add(tableName);
        }
        result.put("operation", operation);
        result.put("tableList", tableList);
        return result;
    } catch (JSQLParserException e) {
        log.error("SQL解析异常,语句为{},原因:", sql, e);
        return result;
    }
}

/**
 * 对select语句解析
 *
 * @param result     表名集合
 * @param selectBody select体
 */
public static void getSelectTables(Set<String> result, SelectBody selectBody) {
    if (selectBody instanceof PlainSelect) {
        PlainSelect plainSelect = (PlainSelect) selectBody;
        FromItem fromItem = plainSelect.getFromItem();
        // 单表
        if (fromItem instanceof Table) {
            Table table = (Table) fromItem;
            String tableName = table.getName();
            result.add(tableName);
        }
        // 子查询
        else if (fromItem instanceof SubSelect) {
            SubSelect subSelect = (SubSelect) fromItem;
            getSelectTables(result, subSelect.getSelectBody());
        }
        // 多表连接查询
        List<Join> joinList = plainSelect.getJoins();
        if (joinList != null) {
            for (Join joinJoin : joinList) {
                FromItem rightFromItem = joinJoin.getRightItem();
                if (!(rightFromItem instanceof Table)) {
                    continue;
                }
                Table table = (Table) rightFromItem;
                String tableName = table.getName();
                result.add(tableName);
            }
        }
    }
    // union连接
    else if (selectBody instanceof SetOperationList) {
        SetOperationList setOperationList = (SetOperationList) selectBody;
        List<SelectBody> selectBodyList = setOperationList.getSelects();
        selectBodyList.forEach(e -> getSelectTables(result, e));
    }
}

2.使用Druid解析

  1. 引入依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.22</version>
</dependency>
  1. 工具方法解析
public static Map<String, Object> parser(String sql) {
    Map<String, Object> result = new HashMap<>();

    MySqlStatementParser parser = new MySqlStatementParser(sql);
    // 是否保留注释
    parser.setKeepComments(false);
    SQLStatement stmt = parser.parseStatement();
    if (stmt instanceof SQLCreateProcedureStatement) {
        SQLCreateProcedureStatement procStmt = (SQLCreateProcedureStatement) stmt;
        SQLStatement blockStmt = procStmt.getBlock();
        if (blockStmt instanceof SQLBlockStatement) {
            SQLBlockStatement sqlBlockStatement = (SQLBlockStatement) blockStmt;
            List<SQLStatement> sqlStatementList = sqlBlockStatement.getStatementList();
            for (SQLStatement statement : sqlStatementList) {
                List<String> tableList = getTableList(statement);
            }
        }
        // List<SQLStatement> statementList = blockStmt.getStatementList();
        // for (SQLStatement sqlStatement : statementList) {
        //     if (sqlStatement instanceof SQLSelectStatement) {
        //         SQLSelectStatement selectStatement = (SQLSelectStatement) sqlStatement;
        //         SQLSelectQuery query = selectStatement.getSelect().getQuery();
        //
        //         // 处理SELECT语句
        //         System.out.println(query.toString());
        //     }
        // }
    }

    return result;
}

public static List<String> getTableList(SQLStatement statement) {
    List<String> result = new ArrayList<>();
    if (statement instanceof SQLSelectStatement) {
        SQLSelectStatement sqlSelectStatement = (SQLSelectStatement) statement;
        SQLSelect sqlSelect = sqlSelectStatement.getSelect();
        SQLSelectQuery sqlSelectQuery = sqlSelect.getQuery();
        if (sqlSelectQuery instanceof MySqlSelectQueryBlock) {
            MySqlSelectQueryBlock mySqlSelectQueryBlock = (MySqlSelectQueryBlock) sqlSelectQuery;
            SQLTableSource sqlTableSource = mySqlSelectQueryBlock.getFrom();
            result.add(sqlTableSource.toString());
        }
    }
    return result;
}
以下是使用jsqlparser解析子查询sql的示例代码: ```java import java.io.StringReader; import java.util.List; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SubSelect; public class JSqlParserDemo { public static void main(String[] args) throws JSQLParserException { String sql = "SELECT * FROM (SELECT * FROM table1 WHERE id IN (SELECT id FROM table2)) AS subquery"; Statement statement = CCJSqlParserUtil.parse(sql); Select selectStatement = (Select) statement; PlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody(); SubSelect subSelect = (SubSelect) plainSelect.getFromItem(); Select subquery = (Select) subSelect.getSelectBody(); PlainSelect subqueryPlainSelect = (PlainSelect) subquery.getSelectBody(); List<Expression> expressions = subqueryPlainSelect.getSelectItems(); for (Expression expression : expressions) { System.out.println(expression.toString()); } } } ``` 上述代码中,我们首先将子查询sql语句作为字符串传入JSqlParser进行解析。然后,我们通过获取Select对象和PlainSelect对象来获取子查询的Select对象和PlainSelect对象。最后,我们可以通过获取子查询的PlainSelect对象来获取子查询中的Select字段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值