anltr 解析MYSQL

String sql = "select a as c,b as s,'zhange' F, 1/5 as e from t_order";

        final MysqlQueryLexer mySqlLexer = new MysqlQueryLexer(CharStreams.fromString(sql));

        final CommonTokenStream commonTokenStream = new CommonTokenStream(mySqlLexer);

        final MysqlQueryParser mySqlParser = new MysqlQueryParser(commonTokenStream);

        mySqlParser.addParseListener(new MysqlQueryBaseListener());

        final MysqlQueryParser.SelectStatementContext selectStatementContext = mySqlParser.selectStatement();
        for (ParseTree child : selectStatementContext.children) {
            if (child instanceof MysqlQueryParser.SelectElementsContext) {
                List<ParseTree>  columnElementContextList = ((MysqlQueryParser.SelectElementsContext) child).children;
                for (int i = 0; i < columnElementContextList.size(); i++) {
                    ParseTree tree = columnElementContextList.get(i);
                    if (tree instanceof MysqlQueryParser.SelectColumnElementContext) {
                        MysqlQueryParser.SelectColumnElementContext columnElementContext = (MysqlQueryParser.SelectColumnElementContext) tree;
                        System.out.println(columnElementContext.fullColumnName());
                        System.out.println(columnElementContext.start.getText() + "----------" + columnElementContext.start.getType());
                        System.out.println(columnElementContext.stop.getText());
                    }
                }
            }
            System.out.println(child.getText() + "------"  );

        }
posted @ 2021-08-11 00:27  酒窝没有酒  阅读(138)  评论(0编辑  收藏  举报