Public classsqlformat{ Public Static voidMain (string[] args) {String SQL=""; Sqlformat (SQL); } Public Staticmap<string, string> map =NewHashmap<string, string> ();//fields that require line breaks Public StaticMap<string, string> bracket=NewHashmap<string, string> ();//pre-parenthesis keyword Static{map.put ("Select", "select"); Map.put (' From ', ' from '); Map.put ("GROUP BY" and "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 (); intsj=0;//string[] Sqlarray= Sql.split ("\\|"); intLength =sqlarray.length; Stack Stack=NewStack (); Stack stacktemp=NewStack (); for(inti=0;i<length; i++){ if("(". Equals (Sqlarray[i]). Trim ())) { if(Map.get (Sqlarray[i+1].trim ())! =NULL{//after keyword Stack.push ("("); Printlnsql (Sqlarray[i], SJ); }Else if(Bracket.get (Sqlarray[i-1].trim ())! =NULL{//before the keyword 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 voidPrintlnsql (String sqlsub,inti) { if(i>0) {System.out.println ("\ n"); for(intj=0; j<i; J + +) {System.out.println ("\t\t"); } }Else{System.out.println (' \ n ' +sqlsub); } }}
Java Formatting for SQL