public classSqlFormat{public static voidmain(String[] args){
String sql="";
sqlFormat(sql);
}public static Map map = new HashMap();//需要换行的字段
public static Map bracket= new HashMap();//括号前关键字
static{
map.put("select", "select");
map.put("from", "from");
map.put("group by", "group by");
map.put("where", "where");
map.put("order by", "order by");
bracket.put("not", "not");
map.put("(", "(");
map.put(")", ")");
}public staticString SqlFormat(String sql){
sql= sql.trim().replaceAll(",", ", ").replaceAll(" +", " ").replaceAll("\\s+", " ").replace(" ", " |").replace("(", "|(|").replace(")", "|)|").replace("| |", " |").replace("||", "|");
sql=sql.toLowerCase();int sj=0;//String[] sqlArray= sql.split("\\|");int length =sqlArray.length;
Stack stack= newStack();
Stack stackTemp= newStack();for(int i=0;i
stack.push("(");
printlnSql(sqlArray[i], sj);
}else if(bracket.get(sqlArray[i-1].trim())!=null){//前有关键字
stack.push("(");
printlnSql(sqlArray[i], sj);
}else{
stackTemp.push("(");
System.out.println(sqlArray[i]);
}
}else if(")".equals(sqlArray[i].trim())){if(stackTemp.size()>0){
stackTemp.pop();
System.out.println(sqlArray[i]);
}else{
stackTemp.pop();
sj=stack.size();
printlnSql(sqlArray[i], sj);
}
}else if("".equals(sqlArray[i].trim())){
}else if("(".equals(sqlArray[i].trim()) && map.get(sqlArray[i-1].trim())!=null){
}else if(map.get(sqlArray[i].trim())!=null){
printlnSql(sqlArray[i], sj);
}else{
System.out.print(sqlArray[i]);
}
}returnsql;
}
pubulicstatic void printlnSql(String sqlSub, inti){if(i>0){
System.out.println("\n");for(int j=0; j
System.out.println("\t\t");
}
}else{
System.out.println(‘\n‘+sqlSub);
}
}
}