| 5 | */ |
| 6 | public class SQLTool { |
| 7 | public static String escapeSql(String raw){ |
| 8 | StringBuilder sb = null; |
| 9 | int[] codePoints = raw.codePoints().toArray(); |
| 10 | for (int i = 0; i < codePoints.length; i++) { |
| 11 | int codePoint = codePoints[i]; |
| 12 | if (codePoint == '%' || codePoint == '_' || codePoint == '\\' || codePoint == '\''){ |
| 13 | if (sb == null){ |
| 14 | sb = new StringBuilder(codePoints.length * 2); |
| 15 | boolean start = true; |
| 16 | for (int j = 0; j < i; j++) { |
| 17 | if (Character.isWhitespace(codePoints[j]) && start){ |
| 18 | continue; |
| 19 | }else { |
| 20 | sb.appendCodePoint(codePoints[j]); |
| 21 | start = false; |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | sb.appendCodePoint('\\'); |
| 26 | sb.appendCodePoint(codePoint); |
| 27 | if (codePoint == '\\'){ |
| 28 | sb.appendCodePoint('\\'); |
| 29 | } |
| 30 | }else { |
| 31 | if (sb != null){ |
| 32 | sb.appendCodePoint(codePoint); |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | if (sb != null){ |
| 38 | int length = sb.length(); |
| 39 | for (int i = codePoints.length - 1; i >= 0; i--) { |
| 40 | if (Character.isWhitespace(codePoints[i])){ |
| 41 | length--; |
| 42 | }else { |
| 43 | break; |
| 44 | } |
| 45 | } |
| 46 | sb.setLength(length); |
| 47 | } |
| 48 | return sb == null ? raw.trim() : sb.toString(); |
| 49 | } |
| 50 | |
| 51 | } |