Java String Sanitize sanitizeStringAsLiteral(String literal)

Here you can find the source of sanitizeStringAsLiteral(String literal)

Description

Sanitize a String for use in a SQL statement

License

Open Source License

Declaration

static String sanitizeStringAsLiteral(String literal) 

Method Source Code

//package com.java2s;
/*/* ww  w.ja  va2 s. c  o  m*/
 * Copyright 2015, Yahoo Inc.
 * Copyrights licensed under the Apache 2.0 License.
 * See the accompanying LICENSE file for terms.
 */

public class Main {
    /**
     * Sanitize a {@link String} for use in a SQL statement
     */
    static String sanitizeStringAsLiteral(String literal) {
        if (literal == null) {
            return "NULL";
        }
        String sanitizedLiteral = literal.replace("'", "''");
        int nullIndex = sanitizedLiteral.indexOf('\0');
        if (nullIndex >= 0) {
            StringBuilder builder = new StringBuilder();
            int start = 0;
            while (nullIndex >= 0) {
                String substr = sanitizedLiteral
                        .substring(start, nullIndex);
                if (substr.length() > 0) { // Append sanitized component before the null
                    builder.append("'").append(substr).append("' || ");
                }
                builder.append("CAST(ZEROBLOB(");
                int blobLength = 1;
                while (nullIndex + 1 < sanitizedLiteral.length()
                        && sanitizedLiteral.charAt(nullIndex + 1) == '\0') { // If there are many adjacent nulls, combine
                    blobLength++;
                    nullIndex++;
                }
                builder.append(blobLength).append(") AS TEXT)"); // Close the cast
                start = nullIndex + 1;
                if (start < sanitizedLiteral.length()) { // If there's more left, continue concatenating
                    builder.append(" || ");
                }
                nullIndex = sanitizedLiteral.indexOf('\0', start);
            }
            if (start < sanitizedLiteral.length()) { // Append final sanitized component
                String substr = sanitizedLiteral.substring(start);
                if (substr.length() > 0) {
                    builder.append("'").append(substr).append("'");
                }
            }
            return builder.toString();
        } else {
            return "'" + sanitizedLiteral + "'";
        }
    }
}

Related

  1. sanitizeString(String input)
  2. sanitizeString(String s)
  3. sanitizeString(String s)
  4. sanitizeString(String s)
  5. sanitizeString(String str)
  6. sanitizeStringForXPath(String text)
  7. sanitizeStringLiteral(String inputString)
  8. sanitizeSuiteName(String name)
  9. sanitizeTag(String s)