SQL解析

 1     private static String getCountSql(String sql) {
 2         return "select count(*) from "+cutOrderByOrGroupBy(getFromHql(sql));
 3     }
 4     
 5     private static String cutOrderByOrGroupBy(String hql) {
 6         int lastFromIndex = hql.lastIndexOf(" from ");
 7         int lastOG = hql.lastIndexOf(" order by ");
 8         if (lastOG < 0) {
 9             lastOG = hql.lastIndexOf(" group by ");
10         }
11         if (lastFromIndex < lastOG) {
12             return hql.substring(0, lastOG);
13         }
14         return hql;
15     }
16     
17     private static String getFromHql(String sql) {
18         String tmpSql = sql;
19         int fIndex = tmpSql.indexOf(" from ");
20         tmpSql = tmpSql.substring(fIndex+5);
21         //确保from没被( 和 )包裹起来,即为该语句主from
22         if (!equalOpenAndCloseParenthesis(tmpSql)) {
23             tmpSql = getFromHql(tmpSql);
24         }
25         return tmpSql;
26     }
27 
28     private static Boolean equalOpenAndCloseParenthesis(String subSql) {
29         final Pattern opPattern = Pattern.compile("\\(");
30         final Matcher opMatch = opPattern.matcher(subSql);
31         final List<String> opMatches = new ArrayList<String>();
32         while (opMatch.find()) {
33             opMatches.add(opMatch.group(0));
34         }
35         final Pattern cpPattern = Pattern.compile("\\)");
36         final Matcher cpMatch = cpPattern.matcher(subSql);
37         final List<String> cpMatches = new ArrayList<String>();
38         while (cpMatch.find()) {
39             cpMatches.add(cpMatch.group(0));
40         }
41         return opMatches.size() == cpMatches.size();
42     }

根据from左右两侧括号情况判断某个from是否是主sql的from关键字。

转载于:https://www.cnblogs.com/justbeginning/p/10606030.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值