JSqlParser⼊门系列(4)-JSqlParser之SQL解析
前⾔
JSqlParser可以解析SQL为JAVA对象,以便于获取SQL中的相关信息并进⾏修改。
⼀般使⽤CCJSqlParserUtil⼯具类直接解析SQ;,根据SQL类型转换为增删改查对象,再获取或修改对象中相关信息。查询解析
/**
* SQL 解析
*
* @throws JSQLParserException
*/
@Test
public void testSelectParser()throws JSQLParserException {
String SQL002 ="SELECT t1.a , t1.b  FROM tab1 AS t1 JOIN tab2 t2 ON t1.user_id  = t2.user_id";// 多表SQL // 1.解析表名
CCJSqlParserManager parserManager =new CCJSqlParserManager();
Statement statement = parserManager.parse(new StringReader(SQL002));// 解析SQL为Statement对象
TablesNamesFinder tablesNamesFinder =new TablesNamesFinder();// 创建表名发现者对象
List<String> tableNameList = TableList(statement);// 获取到表名列表
if(!CollectionUtils.isEmpty(tableNameList)){
tableNameList.::println);// 循环打印解析到的表名 tab1 tab2
}
// 2.解析查询元素=》列,函数等
Select select =(Select) CCJSqlParserUtil.parse(SQL002);
PlainSelect plainSelect =(PlainSelect) SelectBody();
List<SelectItem> selectItems = SelectItems();
selectItems.::println);// t1.a , t1.b
// 3.解析WHERE条件
String SQL_WHERE ="SELECT *  FROM tableName WHERE ID = 8";
PlainSelect plainSelectWhere =(PlainSelect)((Select) CCJSqlParserUtil.parse(SQL_WHERE)).getSelectBody();
EqualsTo equalsTo =(EqualsTo) Where();
Expression leftExpression = LeftExpression();
Expression rightExpression = RightExpression();
// 4.解析Join
List<Join> joins = Joins();
joins.forEach(e ->{
Expression onExpression = e.getOnExpression();
});
// 5.解析IN
String SQL_IN ="SELECT *  FROM tableName WHERE ID IN (8,9,10)";
PlainSelect plainSelectIn =(PlainSelect)((Select) CCJSqlParserUtil.parse(SQL_IN)).getSelectBody();
InExpression inExpression =(InExpression) Where();
ItemsList rightItemsList = RightItemsList();
// Distinct();
// Fetch();
// First();
// GroupBy();
// .......
}
插⼊解析
/**
* Insert 解析
*
* @throws JSQLParserException
*/
@Test
public void testInsertParser()throws JSQLParserException {
javaparser野外// 3.解析WHERE条件
String insertSql ="INSERT INTO test ( c1,c2) VALUES ( 001,002)";
Statement statement = CCJSqlParserUtil.parse(insertSql);
if(statement instanceof Insert){
Insert insert =(Insert) statement;
// 添加新列
insert.addColumns(new Column("c3 "));
/
/ 添加新插⼊值
ExpressionList expressionList =(ExpressionList) ItemsList();
}
修改解析
/**
* Update 解析
*
* @throws JSQLParserException
*/
@Test
public void testUpdateParser()throws JSQLParserException {
String updateSql ="UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson' ";        Statement statement = CCJSqlParserUtil.parse(updateSql);
if(statement instanceof Update){
Update update =(Update) statement;
Expression where = Where();// 获取WHERE表达式=》LastName = 'Wilson'
List<Column> columns = Columns();// 获取修改列=》 FirstName
columns.forEach(System.out::println);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。