Druid 解析sql语句获取所涉及的表名

tech2025-05-30  10

最近工作中需要根据select Sql 语句解析获取所有涉及的表名,一开始使用正在表达式,但是复杂的sql语句无法适配。Druid 则很好解析了这个问题。

private static List<String> getTableNameBySql(String sql) { String dbType = JdbcConstants.MYSQL; try { List<String> tableNameList = new ArrayList<>(); //格式化输出 String sqlResult = SQLUtils.format(sql, dbType); logger.info("格式化后的sql:[{}]",sqlResult); List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType); if (CollectionUtils.isEmpty(stmtList)) { logger.info("stmtList为空无需获取"); return Collections.emptyList(); } for (SQLStatement sqlStatement : stmtList) { MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); sqlStatement.accept(visitor); Map<TableStat.Name, TableStat> tables = visitor.getTables(); logger.info("druid解析sql的结果集:[{}]",tables); Set<TableStat.Name> tableNameSet = tables.keySet(); for (TableStat.Name name : tableNameSet) { String tableName = name.getName(); if (StringUtils.isNotBlank(tableName)) { tableNameList.add(tableName); } } } logger.info("解析sql后的表名:[{}]",tableNameList); return tableNameList; } catch (Exception e) { logger.error("**************异常SQL:[{}]*****************\\n",sql); logger.error(e.getMessage(),e); } return Collections.emptyList(); }
最新回复(0)