Quote a field for a SQL query. - Java java.lang

Java examples for java.lang:String Quote

Description

Quote a field for a SQL query.

Demo Code


//package com.java2s;

public class Main {
    /**/*from   w w w  .  j  a v  a  2s . co m*/
     * Quote a field for a SQL query. If the argument is null, the string
     * "NULL" is returned.
     *
     * @param <T>
     * the type to quote
     * @param arg
     * the argument to be escaped and quoted
     * @return the original string quoted and escaped
     */
    public static <T> String quote(final T arg) {
        if (arg == null) {
            return "NULL";
        }
        return "'" + escape(arg.toString()) + "'";
    }

    /**
     * Quote and zero pad a field for a SQL query.
     *
     * @param value
     * the value to be quoted and zero padded
     * @param length
     * the length of the zero-padded long, excluding the
     * quotes
     * @return the quoted and zero-padded long value
     */
    public static String quote(final long value, final int length) {
        return "'" + zeroPad(value, length) + "'";
    }

    /**
     * Escape single quotes.
     *
     * @param arg
     * the String to escape
     * @return escaped String
     */
    public static String escape(final String arg) {
        return arg.replaceAll("'", "''");
    }

    /**
     * Zero pad the argument until it reach the specified length.
     *
     * @param arg
     * the argument to pad
     * @param length
     * the desired length
     * @return a zero-padded string
     */
    public static String zeroPad(final long arg, final int length) {
        String valueString = "" + arg;
        if (valueString.length() > length) {
            throw new IllegalArgumentException(
                    "Long attribute overflow for " + valueString
                            + " (length " + valueString.length() + ")");
        }
        StringBuilder format = new StringBuilder("%0");
        format.append(length).append("d");
        return String.format(format.toString(), arg);
    }
}

Related Tutorials