随意一条查询sql转换为查询结果集相应的数目
原思路: 像括号配对一样,假设遇见select 就入栈,假设遇见from就出栈,直到栈为空,取得此时的位置。进行字符串截取。
实现方法:遇见字符s而且连续后5个字符elect 就+1,遇见字符f而且连续3个字符为rom就-1,当计数器结果为0时,返回当前字符的位置,然后进行字符串截取就可以:
/**** * 获取截取位置 * @param selectSQL * @return */ public static int getSubIndex(String selectSQL){ System.out.println(selectSQL.length()); int count = 0; for(int i=0;i<selectSQL.length();i++){ char c = selectSQL.charAt(i); if(c =='s'){ if(selectSQL.charAt(i+1)=='e'&&selectSQL.charAt(i+2)=='l'&& selectSQL.charAt(i+3)=='e'&&selectSQL.charAt(i+4)=='c'&& selectSQL.charAt(i+5)=='t'){ count++; i=i+5; }else{ continue; } }else if(c =='f'){ if(selectSQL.charAt(i+1)=='r'&&selectSQL.charAt(i+2)=='o'&& selectSQL.charAt(i+3)=='m'){ count--; i=i+3; System.out.println(count); if(count == 0){ System.out.println(i); return i+1; } }else{ continue; } }else { continue; } } return -1; }
进行字符截取操作:
/** * 进行字符串截取 * @param inSQL * @return */ public static String getOutSQL(String inSQL){ int index = getSubIndex(inSQL); if(index != -1){ String outSQL = "select count(-1) from " + inSQL.substring(index); return outSQL; }else{ System.out.println("not a corrent sql"); return "not a corrent sql"; } }