Provide a single-quoted, properly escaped String for the given value to be used in a SQL statement. - Java java.sql

Java examples for java.sql:PreparedStatement

Description

Provide a single-quoted, properly escaped String for the given value to be used in a SQL statement.

Demo Code


import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;

public class Main{
    /**//ww w .  j  av a2  s.c o  m
     * Provide a single-quoted, properly escaped String for the given
     * value to be used in a SQL statement.
     *
     * Apostrophes will always be escaped as ''.  Backslashes will
     * be escaped as \\ if backslashIsEscape is given as <code>true</code>.
     *
     * @param in The input value.
     * @param backslashIsEscape Whether backslash characters are treated
     *        as escape characters by the underlying database implementation,
     *        and thus need to be escaped themselves.
     * @return the escaped string.
     */
    public static String quotedString(final String in,
            final boolean backslashIsEscape) {
        StringBuffer out = new StringBuffer();
        out.append('\'');
        for (int i = 0; i < in.length(); i++) {
            char c = in.charAt(i);
            if (c == '\'') {
                out.append("''"); //  ' ==> ''
            } else if (backslashIsEscape && c == '\\') {
                out.append("\\\\"); //  \ ==> \\
            } else {
                out.append(c);
            }
        }
        out.append('\'');
        return out.toString();
    }
}

Related Tutorials