package com.wxq.study.utils;
/*
- 本文借鉴了 ITeye 作者:53873039oycg
- Java简单应用之去除SQL文件注释
- https://www.iteye.com/blog/53873039oycg-2018780
- 的文章。感谢作者的付出。
- 53873039oycg 的方法是删除掉sql脚本中的注释信息,但是会把
- sql中的条件值里的类似注释信息也删除掉
- 例如: where a.id = a.id=’/*test–test2 ‘test3’;’
- 在其启发下,完善其bug.
*/
public class ParseSqlFromPostMan {
//删除掉sql中的注释信息,但是不删除 条件中的类似注释信息 例如 a.id='/*test--test2 \'test3\''
public static String deleteZhuShiInfo(String sql)
throws Exception {
String[] split = sql.split("\n");
StringBuffer contentBuffer = new StringBuffer();
boolean isStart = false;
for(int i=0;i<split.length;i++){
StringBuffer temp = new StringBuffer();
char[] charArray = split[i].toCharArray();
for(int j=0;j<charArray.length;) {
char c = charArray[j];
// 单引号里面的类似注释的字符继续保留
if( c == ‘’’) {
if(!isStart) { //前一行已有/* 的标记,就不必添加后面的字符,直到 遇到 / 标记值改变
temp.append©;
j++;
//存在多个 'test’test’的时候怎么递归
int k = getSingleParamInfo(charArray,j,temp);
j=k;
}else {
j++;
}
}else {
if(j<charArray.length-1) {
// 遇到/ 的情况 ,则中间所有的字符都不添加 ,知道遇到 /才结束
if(c == ‘/’&& charArray[j+1] == '’) {
isStart = true;
j++;
for(;j<charArray.length;) {
char c1 = charArray[j];
if(j<charArray.length-1) {
if(c1 == ‘*’&& charArray[j+1] == ‘/’) {
j++;
isStart = false;
break;
}else {
j++;
}
}else {
j++;
}
}
}else if(c == '*'&& charArray[j+1] == '/') {
isStart = false;
j+=2;
continue;
}else if(c == '-'&& charArray[j+1] == '-') {
// --的情况
break;
}else {
j++;
}
if(!isStart) {
temp.append(c);
}
}else {
if(!isStart) {
temp.append(c);
}
j++;
}
}
}
contentBuffer.append(temp.toString());
}
return contentBuffer.toString();
}
private static int getSingleParamInfo(char [] charArray ,int j,StringBuffer temp) {
for(;j<charArray.length;) {
char c = charArray[j];
temp.append(c);
if( c == '\\' && charArray[j+1] == '\'') {
j++;
temp.append(charArray[j]); //添加\'
j++;
// getSingleParamInfo(charArray,j,temp);
}else if(c == ‘’’) {
j++;
break ;
}else {
j++;
}
}
return j;
}
}