1.在maven中引入jsqlparser依赖
<!--sql语句解析-->
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>4.4</version>
</dependency>
2.解析SQL语句具体代码
此代码解析了sql语句,并且判断ddl类型是否是create,如果是create就查出表名
public List<String> getTableInfo(String sqlDDl) {
//解析数据库获取表名
List<String> tableList = new ArrayList<>();
try {
Statements statements = CCJSqlParserUtil.parseStatements(sqlDDl);
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
logger.info("statement->{}", statements);
if (CollectionUtils.isNotEmpty(statements.getStatements())) {
statements.getStatements().forEach(statement -> {
//判断ddl类型是否是create类型 ,如果想获取ddl所有语句的表名,这条代码去掉
if (statement instanceof CreateTable) {
List<String> tableList1 = tablesNamesFinder.getTableList(statement);
if (CollectionUtils.isNotEmpty(tableList1)) {
tableList.add(tableList1.get(0));
logger.info("table->{}", tableList1);
}
}
});
}
} catch (JSQLParserException e) {
e.printStackTrace();
}
}
3.解析SQL语句, 获取表名
4.如果是hive语句,带有特殊字符解析会报错,用正则表达式去除
@Test
public void senDdlMq() {
String sqlDDl = "drop table if exists test_table05;" +
"\ncreate table test_table05 (\nid int comment '自增ID',\nphone varchar(255) comment '手机号'" +
") " +
"row FORMAT DELIMITED FIELDS TERMINATED by ',' stored AS textfile;";
sqlDDl = sqlDDl.replaceAll("\r|\n"," ");
sqlDDl = sqlDDl.replaceAll("(?i)ROW.*?(?=;)", " ");
logger.info("sqlDDl:"+sqlDDl);
List<String> tableInfo = getTableInfo(sqlDDl);
}
“ . ”表示任意字符,“ ? ”表示匹配一次或多次,“ ?<=A ” 表示以A开头、不替换A,“ ?=B ”表示以B结尾、不替换B,“(?i)”表示不区分大小写