Java String Quote quote(String str)

Here you can find the source of quote(String str)

Description

Escape data to protected against SQL Injection

License

Open Source License

Parameter

Parameter Description
link a parameter
str a parameter

Exception

Parameter Description
Exception an exception

Declaration


public static String quote(String str) throws Exception 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from  ww w . j av a  2  s.  c o m*/
     * Escape data to protected against SQL Injection
     *
     * @param link
     * @param str
     * @return
     * @throws Exception 
     */

    public static String quote(String str) throws Exception {
        if (str == null) {
            return "NULL";
        }
        return "'" + mysql_real_escape_string(str) + "'";
    }

    /**
     * Escape string to protected against SQL Injection
     *
     * You must add a single quote ' around the result of this function for data,
     * or a backtick ` around table and row identifiers. 
     * If this function returns null than the result should be changed
     * to "NULL" without any quote or backtick.
     *
     * @param link
     * @param str
     * @return
     * @throws Exception 
     */

    public static String mysql_real_escape_string(String str) throws Exception {
        if (str == null) {
            return null;
        }

        if (str.replaceAll("[a-zA-Z0-9_!@#$%^&*()-=+~.;:,\\Q[\\E\\Q]\\E<>{}\\/? ]", "").length() < 1) {
            return str;
        }

        String clean_string = str;
        clean_string = clean_string.replaceAll("\\\\", "\\\\\\\\");
        clean_string = clean_string.replaceAll("\\n", "\\\\n");
        clean_string = clean_string.replaceAll("\\r", "\\\\r");
        clean_string = clean_string.replaceAll("\\t", "\\\\t");
        clean_string = clean_string.replaceAll("\\00", "\\\\0");
        clean_string = clean_string.replaceAll("'", "\\\\'");
        clean_string = clean_string.replaceAll("\\\"", "\\\\\"");

        if (clean_string.replaceAll("[a-zA-Z0-9_!@#$%^&*()-=+~.;:,\\Q[\\E\\Q]\\E<>{}\\/?\\\\\"' ]", "")
                .length() < 1) {
            return clean_string;
        }

        return clean_string;
    }
}

Related

  1. quote(String s)
  2. quote(String s)
  3. quote(String s, char ch)
  4. quote(String s, String nullResult)
  5. quote(String s, String specials, char quoteChar)
  6. quote(String str)
  7. quote(String str)
  8. quote(String str)
  9. quote(String str)