简单写了个小工具,用来获取SQL中的数据来源表
代码如下:
package com.app.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.druid.util.JdbcConstants;
public class AnalysisSQL {
public static List<String> analysisSQL(String sql){
if(sql == null || sql.length() < 1) return null;
List<String> res = new ArrayList<>();
String dbType = JdbcConstants.MYSQL;
//格式化sql
String result = SQLUtils.format(sql, dbType);
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
//循环执行多个语句
for (int i = 0; i < stmtList.size(); i++) {
SQLStatement stmt = stmtList.get(i);
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
//获取SQL中的表名和操作方法名的map
for (Map.Entry<TableStat.Name, TableStat> entry : visitor.getTables().entrySet()) {
res.add(entry.getKey().toString());
}
}
return res;
}
}
maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.17</version>
</dependency>