这里使用到了druid
的MySqlStatementParser
类解析sql
。
public static void main(String[] args) {
MySqlStatementParser mySqlStatementParser = new MySqlStatementParser("select name,price from tb_order where id in (select id from tb_order where id = 1)");
SQLSelectStatement sqlSelectStatement = mySqlStatementParser.parseSelect();
SQLSelect sqlSelect = sqlSelectStatement.getSelect();
SQLSelectQuery sqlSelectQuery = sqlSelect.getQuery();
if (sqlSelectQuery instanceof MySqlSelectQueryBlock) {
MySqlSelectQueryBlock mySqlSelectQueryBlock = (MySqlSelectQueryBlock) sqlSelectQuery;
MySqlOutputVisitor where = new MySqlOutputVisitor(new StringBuilder());
// 获取where 条件
mySqlSelectQueryBlock.getWhere().accept(where);
System.out.println("##########where###############");
System.out.println(where.getAppender() );
// 获取表名
System.out.println("############table_name##############");
MySqlOutputVisitor tableName = new MySqlOutputVisitor(new StringBuilder());
mySqlSelectQueryBlock.getFrom().accept(tableName);
System.out.println(tableName.getAppender());
// 获取查询字段
System.out.println("############查询字段##############");
System.out.println(mySqlSelectQueryBlock.getSelectList());
}
}