测试代码
public void getTableNamesFromSql(){
String sql = "select gender,email,phone,address from table1 where id = 3 and name = 'dave'";
String dbType = JdbcConstants.MYSQL;
try {
List<String> tableNameList = new ArrayList<>();
String sqlResult = SQLUtils.format(sql, dbType);
log.info("格式化后的sql:[{}]",sqlResult);
List<SQLStatement> stmtList = null;
try {
stmtList = SQLUtils.parseStatements(sql, dbType);
} catch (ParserException e) {
log.error("sql语法有误,请检查sql:{}",e.getMessage());
return;
}
if (CollectionUtils.isEmpty(stmtList)) {
log.info("stmtList为空无需获取");
}
for (SQLStatement sqlStatement : stmtList) {
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
sqlStatement.accept(visitor);
Map<TableStat.Name, TableStat> tables = visitor.getTables();
log.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);
}
}
List<TableStat.Condition> conditions = visitor.getConditions();
log.info("解析sql后的查询条件:{}",conditions);
Collection<TableStat.Column> columns = visitor.getColumns();
log.info("解析sql后的字段:{}",columns);
}
log.info("解析sql后的表名:[{}]",tableNameList);
} catch (Exception e) {
log.error("**************异常SQL:[{}]*****************\\n",sql);
log.error(e.getMessage(),e);
}
}
运行结果