maven
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>4.9</version>
</dependency>
解析SQL
String sql = "select aa,bb from b";
Statement statement=CCJSqlParserUtil.parse(sql);
Select selectStatement = (Select) statement;
PlainSelect plainSelect = selectStatement.getPlainSelect();
//plainSelect可以获取sql各个部分 如属性集合
List<SelectItem<?>> selectItems0 = plainSelect.getSelectItems();
分析
Statement 被设计成一个接口满足CURD各个处理方式
1、查询PlainSelect继承Select
1.1//字段起别名 SELECT aa AS ALIAS1, bb AS ALIAS2 FROM b
AddAliasesVisitor instance = new AddAliasesVisitor();
instance.setPrefix("alias");
selectStatement.accept(instance);
1.2//加字段SELECT aa AS ALIAS1, bb AS ALIAS2, field FROM b
SelectUtils.addExpression(selectStatement, new Column("field"));
1.3//加字段表达式 SELECT aa AS ALIAS1, bb AS ALIAS2, field, 5 + 6 FROM b
Addition add = new Addition();
add.setLeftExpression(new LongValue(5));
add.setRightExpression(new LongValue(6));
SelectUtils.addExpression(selectStatement, add);
1.4//加join
//SELECT aa AS ALIAS1, bb AS ALIAS2, field, 5 + 6 FROM b LEFT JOIN mytable2 ON a = b
EqualsTo equalsTo = new EqualsTo();
Statement select = (PlainSelect) test(sql);
equalsTo.setLeftExpression(new Column("a"));
equalsTo.setRightExpression(new Column("b"));
Join addJoin = SelectUtils.addJoin(selectStatement, new Table("mytable2"), equalsTo);
addJoin.setLeft(true);
//SelectUtils构建一个SQL语句
Select selectbuild = SelectUtils.buildSelectFromTableAndExpressions(new Table("mytable"), new Column("a"), new Column("b"));
//SELECT a, b, c FROM mytable
SelectUtils.addExpression(selectbuild, new Column("c"));
//where 条件设置
EqualsTo equalsTo1 = new EqualsTo();
equalsTo1.setLeftExpression(new Column("id"));
equalsTo1.setRightExpression(new Column("1"));
PlainSelect plainSelect1 = selectbuild.getPlainSelect();
plainSelect1.setWhere(equalsTo1);
更多条件访问 https://blog.csdn.net/a250152/article/details/128610616
2、插入Insert
3、更新Update
4、删除Delete