Java String Single Quote singleQuoteForSql(String val)

Here you can find the source of singleQuoteForSql(String val)

Description

Encloses a value in single-quotes, to make a SQL string value.

License

Common Public License

Declaration

static String singleQuoteForSql(String val) 

Method Source Code

//package com.java2s;
/*// w w  w  . j  a  v  a  2 s .com
 // $Id: //open/mondrian/src/main/mondrian/rolap/RolapUtil.java#8 $
 // This software is subject to the terms of the Common Public License
 // Agreement, available at the following URL:
 // http://www.opensource.org/licenses/cpl.html.
 // (C) Copyright 2001-2002 Kana Software, Inc. and others.
 // All Rights Reserved.
 // You must accept the terms of that agreement to use this software.
 //
 // jhyde, 22 December, 2001
 */

public class Main {
    /**
     * Encloses a value in single-quotes, to make a SQL string value. Examples:
     * <code>singleQuoteForSql(null)</code> yields <code>NULL</code>;
     * <code>singleQuoteForSql("don't")</code> yields <code>'don''t'</code>.
     **/
    static String singleQuoteForSql(String val) {
        if (val == null) {
            return "NULL";
        }
        String s0 = replace(val, "'", "''");
        return "'" + s0 + "'";
    }

    /**
     * Returns <code>s</code> with <code>find</code> replaced everywhere with
     * <code>replace</code>.
     **/
    static String replace(String s, String find, String replace) {
        // let's be optimistic
        int found = s.indexOf(find);
        if (found == -1) {
            return s;
        }
        StringBuffer sb = new StringBuffer(s.length());
        int start = 0;
        for (;;) {
            for (; start < found; start++) {
                sb.append(s.charAt(start));
            }
            if (found == s.length()) {
                break;
            }
            sb.append(replace);
            start += find.length();
            found = s.indexOf(find, start);
            if (found == -1) {
                found = s.length();
            }
        }
        return sb.toString();
    }
}

Related

  1. singleQuote(String data)
  2. singleQuote(String input)
  3. singleQuote(String s)
  4. singleQuote(String text)
  5. singleQuotedString(String str)
  6. singleQuotize(String s)
  7. singleUnquoted(String string)