sqlparser mysql_Druid的SQL Parser

最近在看zebra的分库分表源码部分所使用的sql解析就是采用的SQL Parser,这里写个简单的举例方便新手理解

简单使用举例

public class SqlParser {

public static void main(String[] args) {

String sql = "select * from t where id=1 and name=ming group by uid limit 1,200 order by ctime";

// 新建 MySQL Parser

SQLStatementParser parser = new MySqlStatementParser(sql);

// 使用Parser解析生成AST,这里SQLStatement就是AST

SQLStatement sqlStatement = parser.parseStatement();

MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();

sqlStatement.accept(visitor);

System.out.println("getTables:" + visitor.getTables());

System.out.println("getParameters:" + visitor.getParameters());

System.out.println("getOrderByColumns:" + visitor.getOrderByColumns());

System.out.println("getGroupByColumns:" + visitor.getGroupByColumns());

System.out.println("---------------------------------------------------------------------------");

// 使用select访问者进行select的关键信息打印

SelectPrintVisitor selectPrintVisitor = new SelectPrintVisitor();

sqlStatement.accept(selectPrintVisitor);

System.out.println("---------------------------------------------------------------------------");

// 最终sql输出

StringWriter out = new StringWriter();

TableNameVisitor outputVisitor = new TableNameVisitor(out);

sqlStatement.accept(outputVisitor);

System.out.println(out.toString());

}

}

/**

* 查询语句访问者

*

* @author xiezhengchao

* @since 2018/6/1 12:08

*/

public class SelectPrintVisitor extends SQLASTVisitorAdapter {

@Override

public boolean visit(SQLSelectQueryBlock x) {

List selectItemList = x.getSelectList();

selectItemList.forEach(selectItem -> {

System.out.println("attr:" + selectItem.getAttributes());

System.out.println("expr:" + SQLUtils.toMySqlString(selectItem.getExpr()));

});

System.out.println("table:" + SQLUtils.toMySqlString(x.getFrom()));

System.out.println("where:" + SQLUtils.toMySqlString(x.getWhere()));

System.out.println("order by:" + SQLUtils.toMySqlString(x.getOrderBy().getItems().get(0)));

System.out.println("limit:" + SQLUtils.toMySqlString(x.getLimit()));

return true;

}

}

/**

* 数据库表名访问者

*

* @author xiezhengchao

* @since 2018/6/1 11:52

*/

public class TableNameVisitor extends MySqlOutputVisitor {

public TableNameVisitor(Appendable appender) {

super(appender);

}

@Override

public boolean visit(SQLExprTableSource x) {

SQLName table = (SQLName) x.getExpr();

String tableName = table.getSimpleName();

// 改写tableName

print0("new_" + tableName.toUpperCase());

return true;

}

}

这里只是简单的使用举例,对于初学者理解了通过访问者对象去获取sql的关键信息即可.具体的访问者还是要看官方文档.

3fb67691d3c8

实际运行结果

例子源码

参考链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值