Here you can find the source of quoteStringSQL(String s)
Parameter | Description |
---|---|
s | the text to convert. |
public static String quoteStringSQL(String s)
//package com.java2s; /*/*from w w w. jav a 2s . c o m*/ * Copyright (c) 2007-2010 Centimia Ltd. * All rights reserved. Unpublished -- rights reserved * * Use of a copyright notice is precautionary only, and does * not imply publication or disclosure. * * Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group, Centimia Inc. */ public class Main { /** * Convert a string to a SQL literal. Null is converted to NULL. The text is * enclosed in single quotes. If there are any special characters, the method * STRINGDECODE is used. * * @param s the text to convert. * @return the SQL literal */ public static String quoteStringSQL(String s) { if (s == null) { return "NULL"; } int length = s.length(); StringBuilder buff = new StringBuilder(length + 2); buff.append('\''); for (int i = 0; i < length; i++) { char c = s.charAt(i); if (c == '\'') { buff.append(c); } else if (c < ' ' || c > 127) { // need to start from the beginning because maybe there was a \ // that was not quoted return "STRINGDECODE(" + quoteStringSQL(javaEncode(s)) + ")"; } buff.append(c); } buff.append('\''); return buff.toString(); } /** * Convert a string to a Java literal using the correct escape sequences. * The literal is not enclosed in double quotes. The result can be used in * properties files or in Java source code. * * @param s the text to convert * @return the Java representation */ public static String javaEncode(String s) { int length = s.length(); StringBuilder buff = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = s.charAt(i); switch (c) { case '\t': // HT horizontal tab buff.append("\\t"); break; case '\n': // LF linefeed buff.append("\\n"); break; case '\f': // FF form feed buff.append("\\f"); break; case '\r': // CR carriage return buff.append("\\r"); break; case '"': // double quote buff.append("\\\""); break; case '\\': // backslash buff.append("\\\\"); break; default: int ch = c & 0xffff; if (ch >= ' ' && (ch < 0x80)) { buff.append(c); } else { buff.append("\\u"); // make sure it's four characters buff.append(Integer.toHexString(0x10000 | ch).substring(1)); } } } return buff.toString(); } }