【组件】JAVA解析SQL语句jsqlparser

jsqlparser

依赖maven

        
        
            com.github.jsqlparser
            jsqlparser
            4.3
        

    public static void main(String[] args) throws Exception {


        String sql = """
                UPDATE
                 t1 q
                 SET q.name  = '张三'
                """;
//        sql = """
//DELETE t1 FROM t1,t2 WHERE t1.id=t2.id
//               """;

        Statement parse = CCJSqlParserUtil.parse(sql);
        //字典
        Dict tableMap = new Dict();
        Dict tableFullMap = new Dict();

        Table table = null;
        FromItem fromItem = null;
        List joins = null;
        List usingList = null;
        Expression where = null;
        if(parse instanceof Insert){
            log.info("增");
            Insert insert = (Insert) parse;
            table = insert.getTable();

        }else if(parse instanceof Delete){
            log.info("删");
            Delete delete = (Delete) parse;
            table = delete.getTable();
            joins = delete.getJoins();
            usingList = delete.getUsingList();
            where = delete.getWhere();

        }else if(parse instanceof Update){
            log.info("改");
            Update update = (Update) parse;
            table = update.getTable();
            joins = update.getJoins();
            fromItem = update.getFromItem();
            where = update.getWhere();

        }else if(parse instanceof Select){
            log.info("查");

        }


        if(table != null){
            log.info("表名:{}", table.getName());
            if(table.getAlias() != null){
                tableMap.set(table.getAlias().getName(), table.getName());
            }else{
                tableMap.set(table.getName(), table.getName());
            }
            tableFullMap.set(table.getName(), table);
        }

        if(fromItem != null){
            Table fromItemTable = (Table) fromItem; // table.getAlias().getName(), table.getName()
            log.info("fromItem表名:{}", fromItemTable.getName());
            if(fromItemTable.getAlias() != null){
                tableMap.set(fromItemTable.getAlias().getName(), fromItemTable.getName());
            }else{
                tableMap.set(fromItemTable.getName(), fromItemTable.getName());
            }
            tableFullMap.set(fromItemTable.getName(), fromItemTable);
        }

        /**
         * 联查
         */
        if(CollUtil.isNotEmpty(joins)){
            for (Join join : joins) {
                FromItem rightItem = join.getRightItem();
                Table table2 = (Table) rightItem; // (table.getAlias().getName(), table.getName());
                log.info("联查表:{}", table2.getName());
                if(table2.getAlias() != null){
                    tableMap.set(table2.getAlias().getName(), table2.getName());
                }else{
                    tableMap.set(table2.getName(), table2.getName());
                }
                tableFullMap.set(table2.getName(), table2);

                // on 条件分析   //和where一样
                Collection onExpressions = join.getOnExpressions();
                for (Expression expression : onExpressions) {
//                EqualsTo equalsTo = (EqualsTo) expression;
                    if (expression instanceof Column) {
                        Column rightColumn = (Column) expression;
                        log.info("联查条件 ON,表名:{}, 字段名:{}, 关联条件:{}", tableMap.get(rightColumn.getTable().toString()), rightColumn.getColumnName());
                    }
                }
            }
        }


        // where 分析
        // where 只有两种情况,一种就是简单的a = b,另外就是 a = b or ... and, 这种就是AndExpression
        if(where != null){
            if (where instanceof EqualsTo) {
                EqualsTo equalsTo = (EqualsTo) where;
                Expression rightExpression = equalsTo.getRightExpression();
                Expression leftExpression = equalsTo.getLeftExpression();
                if (rightExpression instanceof Column) {
                    Column rightColumn = (Column) rightExpression;
                    log.info("条件 RIGHT,表名:{}, 字段名:{}, 值:{}", tableMap.get(rightColumn.getTable().toString()), rightColumn.getColumnName(), equalsTo.getRightExpression());
                }
                if (leftExpression instanceof Column) {
                    Column leftColumn = (Column) leftExpression;
                    log.info("条件 LEFT,表名:{}, 字段名:{}, 值:{}", tableMap.get(leftColumn.getTable().toString()), leftColumn.getColumnName(), equalsTo.getRightExpression());
                }
            }else if(where instanceof AndExpression){
                AndExpression andExpression = (AndExpression) where;
                Expression leftExpression = andExpression.getLeftExpression();
//            doExpression(leftExpression);
                Expression rightExpression = andExpression.getRightExpression();
//            doExpression(rightExpression);
            }
        }

        /**
         * usingList
         */
        if(CollUtil.isNotEmpty(usingList)){
            for (Table table2 : usingList) {

                if(table2.getAlias() != null){
                    tableMap.set(table2.getAlias().getName(), table2.getName());
                }else{
                    tableMap.set(table2.getName(), table2.getName());
                }
                log.info("using表名:{}", table2.getName());

            }
        }

//        System.out.println(parse);
//
//        // 使用工具类把SQL转换为Select对象
//        Select select = (Select) CCJSqlParserUtil.parse("""
//                 SELECT
//                                       *
//                                        FROM
//                                        user u
//                """);
//
//        SelectBody selectBody = select.getSelectBody();
//        PlainSelect plainSelect = (PlainSelect) selectBody;


    }
 
  

工具



import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.Join;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
public class SqlUtil {


    /**
     * 通过sql 解析出涉及到的表
     * @param sql
     * @return
     * @throws Exception
     */
    public static Set getSqlTables(String sql) {


//        String sql = """
//                UPDATE
//                 user u
//                 SET u.name  = '张三'
//                """;
//        sql = """
//DELETE t1 FROM t1,t2 WHERE t1.id=t2.id
//               """;

        Set tables = new HashSet<>();

        Statement parse = null;
        try {
            parse = CCJSqlParserUtil.parse(sql);
        } catch (JSQLParserException e) {
            e.printStackTrace();
            return tables;
        }
        //字典
        Dict tableMap = new Dict();
        Dict tableFullMap = new Dict();

        Table table = null;
        FromItem fromItem = null;
        List joins = null;
        List
usingList = null; Expression where = null; if(parse instanceof Insert){ log.info("增"); Insert insert = (Insert) parse; table = insert.getTable(); }else if(parse instanceof Delete){ log.info("删"); Delete delete = (Delete) parse; table = delete.getTable(); joins = delete.getJoins(); usingList = delete.getUsingList(); where = delete.getWhere(); }else if(parse instanceof Update){ log.info("改"); Update update = (Update) parse; table = update.getTable(); joins = update.getJoins(); fromItem = update.getFromItem(); where = update.getWhere(); }else if(parse instanceof Select){ // log.info("查"); } if(table != null){ // log.info("表名:{}", table.getName()); // if(table.getAlias() != null){ // tableMap.set(table.getAlias().getName(), table.getName()); // }else{ // tableMap.set(table.getName(), table.getName()); // } // tableFullMap.set(table.getName(), table); tables.add(table.getName()); } if(fromItem != null){ Table fromItemTable = (Table) fromItem; // table.getAlias().getName(), table.getName() // log.info("fromItem表名:{}", fromItemTable.getName()); // if(fromItemTable.getAlias() != null){ // tableMap.set(fromItemTable.getAlias().getName(), fromItemTable.getName()); // }else{ // tableMap.set(fromItemTable.getName(), fromItemTable.getName()); // } // tableFullMap.set(fromItemTable.getName(), fromItemTable); tables.add(fromItemTable.getName()); } /** * 联查 */ if(CollUtil.isNotEmpty(joins)){ for (Join join : joins) { FromItem rightItem = join.getRightItem(); Table table2 = (Table) rightItem; // (table.getAlias().getName(), table.getName()); // log.info("联查表:{}", table2.getName()); // if(table2.getAlias() != null){ // tableMap.set(table2.getAlias().getName(), table2.getName()); // }else{ // tableMap.set(table2.getName(), table2.getName()); // } // tableFullMap.set(table2.getName(), table2); tables.add(table2.getName()); // on 条件分析 //和where一样 // Collection onExpressions = join.getOnExpressions(); // for (Expression expression : onExpressions) { EqualsTo equalsTo = (EqualsTo) expression; // if (expression instanceof Column) { // Column rightColumn = (Column) expression; // log.info("联查条件 ON,表名:{}, 字段名:{}, 关联条件:{}", tableMap.get(rightColumn.getTable().toString()), rightColumn.getColumnName()); // } // } } } // where 分析 // where 只有两种情况,一种就是简单的a = b,另外就是 a = b or ... and, 这种就是AndExpression // if(where != null){ // if (where instanceof EqualsTo) { // EqualsTo equalsTo = (EqualsTo) where; // Expression rightExpression = equalsTo.getRightExpression(); // Expression leftExpression = equalsTo.getLeftExpression(); // if (rightExpression instanceof Column) { // Column rightColumn = (Column) rightExpression; // log.info("条件 RIGHT,表名:{}, 字段名:{}, 值:{}", tableMap.get(rightColumn.getTable().toString()), rightColumn.getColumnName(), equalsTo.getRightExpression()); // } // if (leftExpression instanceof Column) { // Column leftColumn = (Column) leftExpression; // log.info("条件 LEFT,表名:{}, 字段名:{}, 值:{}", tableMap.get(leftColumn.getTable().toString()), leftColumn.getColumnName(), equalsTo.getRightExpression()); // } // }else if(where instanceof AndExpression){ // AndExpression andExpression = (AndExpression) where; // Expression leftExpression = andExpression.getLeftExpression(); doExpression(leftExpression); // Expression rightExpression = andExpression.getRightExpression(); doExpression(rightExpression); // } // } /** * usingList */ if(CollUtil.isNotEmpty(usingList)){ for (Table table2 : usingList) { // if(table2.getAlias() != null){ // tableMap.set(table2.getAlias().getName(), table2.getName()); // }else{ // tableMap.set(table2.getName(), table2.getName()); // } // log.info("using表名:{}", table2.getName()); tables.add(table2.getName()); } } // System.out.println(parse); // // // 使用工具类把SQL转换为Select对象 // Select select = (Select) CCJSqlParserUtil.parse(""" // SELECT // * // FROM // user u // """); // // SelectBody selectBody = select.getSelectBody(); // PlainSelect plainSelect = (PlainSelect) selectBody; return tables; } }

你可能感兴趣的:(技巧心得,java,sql,数据库)