结合项目使用,添加依赖或者自己下载相关的jar包
<!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser -->
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>1.4</version>
</dependency>
下面通过自己做的实例来简单了解一下jsqlsparser的使用
jsqlsparser实例:
/***
* 获取select sql表名
* @param sql
* @return
*/
public static List<String> select_table(String sql){
Statement statement = null;
try {
statement = CCJSqlParserUtil.parse(sql);
} catch (JSQLParserException e) {
e.printStackTrace();
}
Select selectStatement = (Select) statement;
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
List<String> tableList = tablesNamesFinder
.getTableList(selectStatement);
return tableList;
}
/**
* 获取insert 表名
* @param sql
* @return
* @throws JSQLParserException
*/
public static String insert_table(String sql) {
Statement statement = null;
try {
statement = CCJSqlParserUtil.parse(sql);
} catch (JSQLParserException e) {
e.printStackTrace();
}
Insert insertStatement = (Insert) statement;
String string_tablename = insertStatement.getTable().getName();
return string_tablename;
}
/**
* 获取insert字段名
* @param sql
* @return
*/
public static List<String> insert_column(String sql) {
Statement statement = null;
try {
statement = CCJSqlParserUtil.parse(sql);
} catch (JSQLParserException e) {
e.printStackTrace();
}
Insert insertStatement = (Insert) statement;
List<Column> table_column = insertStatement.getColumns();
List<String> str_column = new ArrayList<String>();
for (int i = 0; i < table_column.size(); i++) {
str_column.add(table_column.get(i).toString());
}
return str_column;
}
/**
* 获取insert value值
* @param sql
* @return
*/
public static List<String> insert_values(String sql){
Statement statement = null;
try {
statement = CCJSqlParserUtil.parse(sql);
} catch (JSQLParserException e) {
e.printStackTrace();
}
Insert insertStatement = (Insert) statement;
List<Expression> insert_values_expression = ((ExpressionList) insertStatement
.getItemsList()).getExpressions();
List<String> str_values = new ArrayList<String>();
for (int i = 0; i < insert_values_expression.size(); i++) {
str_values.add(insert_values_expression.get(i).toString());
}
return str_values;
}
因为我自己只用到了添加语句的获取方法,但是jar包里基本上都有,可以下载看一下
这个插件挺好用的,直接传入对应的SQL语句就能实现功能
实际调用
//根据SQL语句获取表名 sql[i]为sql语句
String table = DbUtils.insert_table(sql[i]);
//根据SQL语句获取字段集
List <String> column = DbUtils.insert_column(sql[i]);
//根据SQL语句获取参数集
List <String> values = DbUtils.insert_values(sql[i]);
另外查询的获取方法也有可以参考一下源底层代码