Appends an Object to an SQL string with the proper escaping, etc.
761673
public static final void appendValueToSql(StringBuilder sql, Object value) {
        if (value == null) {
            sql.append("NULL");
        } else if (value instanceof Boolean) {
            Boolean bool = (Boolean)value;
            if (bool) {
                sql.append('1');
            } else {
                sql.append('0');
            }
        } else {
            appendEscapedSQLString(sql, value.toString());
        }
    }
1095111
function SQL(strs) {
  for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  var values = [];
  var text = strs.reduce(function (prev, curr, i) {
    var arg = args[i - 1];
    if (arg instanceof InsertValue) {
      return prev + arg.value + curr;
    } else {
      values.push(arg);
      return prev + '$' + values.length + curr;
    }
  });

  return {
    text: text,
    values: values
  };
}
731091
def _sql_expand_insert(self, spec, key_prefix = '', col_prefix = ''):
        
        col = list(spec)
        sql = '('
        sql += ', '.join(col_prefix + key for key in col)
        sql += ') VALUES ('
        sql += ', '.join('%(' + key_prefix + key + ')s' for key in col)
        sql += ')'
        params = {}
        for key in spec:
            params[key_prefix + key] = spec[key]

        return sql, params
1184838
private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)
    {
        if (join.isOuter)
        {
            buf.append(" LEFT OUTER JOIN ");
        }
        else
        {
            buf.append(" INNER JOIN ");
        }
        if (join.right.hasJoins())
        {
            buf.append("(");
            appendTableWithJoins(join.right, where, buf);
            buf.append(")");
        }
        else
        {
            appendTableWithJoins(join.right, where, buf);
        }
        buf.append(" ON ");
        join.appendJoinEqualities(buf);
    }
50735
function buildQueryString (obj) {
  var query = Object.keys(obj).reduce(function (acc, key) {
    return acc + '&' + querystring.escape(key) + '=' +
      querystring.escape(obj[key])
  }, '')
  return query.replace(/^&/, '?')
}
1186059
WrappedStatement compile(String sql) throws SQLException {
    WrappedStatement ws;
    if (! isEnabled(Option.REUSE_STATEMENTS)) {
      ws = new WrappedStatement(connection.prepareStatement(sql), false);
    }
    else {
      if (pool == null) {
        pool = new IdentityHashMap<>();
      }
      String sqlI = sql.intern();
      ws = pool.get(sqlI);
      if (ws == null) {
        ws =  new WrappedStatement(connection.prepareStatement(sql), true);
        pool.put(sqlI, ws);
      }
    }
    return ws;
  }
671613
protected void appendArgOrValue(DatabaseType databaseType, FieldType fieldType, StringBuilder sb,
			List<ArgumentHolder> argList, Object argOrValue) throws SQLException {
		boolean appendSpace = true;
		if (argOrValue == null) {
			throw new SQLException("argument for '" + fieldType.getFieldName() + "' is null");
		} else if (argOrValue instanceof ArgumentHolder) {
			sb.append('?');
			ArgumentHolder argHolder = (ArgumentHolder) argOrValue;
			argHolder.setMetaInfo(columnName, fieldType);
			argList.add(argHolder);
		} else if (argOrValue instanceof ColumnArg) {
			ColumnArg columnArg = (ColumnArg) argOrValue;
			String tableName = columnArg.getTableName();
			if (tableName != null) {
				databaseType.appendEscapedEntityName(sb, tableName);
				sb.append('.');
			}
			databaseType.appendEscapedEntityName(sb, columnArg.getColumnName());
		} else if (fieldType.isArgumentHolderRequired()) {
			sb.append('?');
			ArgumentHolder argHolder = new SelectArg();
			argHolder.setMetaInfo(columnName, fieldType);
			// conversion is done when the getValue() is called
			argHolder.setValue(argOrValue);
			argList.add(argHolder);
		} else if (fieldType.isForeign() && fieldType.getType().isAssignableFrom(argOrValue.getClass())) {
			/*
			 * If we have a foreign field and our argument is an instance of the foreign object (i.e. not its id), then
			 * we need to extract the id. We allow super-classes of the field but not sub-classes.
			 */
			FieldType idFieldType = fieldType.getForeignIdField();
			appendArgOrValue(databaseType, idFieldType, sb, argList, idFieldType.extractJavaFieldValue(argOrValue));
			// no need for the space since it was done in the recursion
			appendSpace = false;
		} else if (fieldType.isEscapedValue()) {
			databaseType.appendEscapedWord(sb, fieldType.convertJavaFieldToSqlArgValue(argOrValue).toString());
		} else if (fieldType.isForeign()) {
			/*
			 * I'm not entirely sure this is correct. This is trying to protect against someone trying to pass an object
			 * into a comparison with a foreign field. Typically if they pass the same field type, then ORMLite will
			 * extract the ID of the foreign.
			 */
			String value = fieldType.convertJavaFieldToSqlArgValue(argOrValue).toString();
			if (value.length() > 0) {
				if (NUMBER_CHARACTERS.indexOf(value.charAt(0)) < 0) {
					throw new SQLException("Foreign field " + fieldType
							+ " does not seem to be producing a numerical value '" + value
							+ "'. Maybe you are passing the wrong object to comparison: " + this);
				}
			}
			sb.append(value);
		} else {
			// numbers can't have quotes around them in derby
			sb.append(fieldType.convertJavaFieldToSqlArgValue(argOrValue));
		}
		if (appendSpace) {
			sb.append(' ');
		}
	}
271378
public synchronized void insert (Connection conn, T obj)
        throws SQLException
    {
        StringBuilder sql = new StringBuilder(
            "insert into " + name + " (" + listOfFields + ") values (?");
        for (int i = 1; i < nColumns; i++) {
            sql.append(",?");
        }
        sql.append(")");
        PreparedStatement insertStmt = conn.prepareStatement(sql.toString());
        bindUpdateVariables(insertStmt, obj, null);
        insertStmt.executeUpdate();
        insertStmt.close();
    }
969466
protected static final void append(StringBuilder builder, String key, String value) {

		// Convert key
		String formattedKey = key.replace('[', '.').replace("]", "");

		// Append key
		char c;
		boolean replace = false;
		char[] chars = formattedKey.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			c = chars[i];
			if ((c > 0xFF) || KEY_ESCAPES[c] != 0) {
				replace = true;
				break;
			}
		}
		if (replace) {
			appendWithEscapes(builder, formattedKey, KEY_ESCAPES);
		} else {
			builder.append(formattedKey);
		}
		builder.append('=');

		// Append value
		if (value != null && !value.isEmpty()) {
			replace = false;
			chars = value.toCharArray();
			for (int i = 0; i < chars.length; i++) {
				c = chars[i];
				if ((c > 0xFF) || VALUE_ESCAPES[c] != 0) {
					replace = true;
					break;
				}
			}
			if (replace) {
				appendWithEscapes(builder, value, VALUE_ESCAPES);
			} else {
				builder.append(value);
			}
		}

		// Line break
		builder.append(LINE_SEPARATOR);
	}
329221
private StringBuilder appendPostTypes(final EnumSet<Post.Type> types, final StringBuilder sql) {
      int typesCount = types != null ? types.size() : 0;
      switch(typesCount) {
         case 0:
            break;
         case 1:
            sql.append(" AND post_type=").append(String.format("'%s'", types.iterator().next().toString()));
            break;
         default:
            sql.append(" AND post_type IN (");
            sql.append(inJoiner.join(types.stream().map(t -> String.format("'%s'", t.toString())).collect(Collectors.toSet())));
            sql.append(")");
            break;
      }

      return sql;
   }
1047127
def update_object_in_db(self,
                            obj: Any,
                            table: str,
                            fieldlist: Sequence[str]) -> None:
        """"""
        self.ensure_db_open()
        pkvalue = getattr(obj, fieldlist[0])
        valuelist = []
        # Non-PK fields first
        for f in fieldlist[1:]:
            valuelist.append(getattr(obj, f))
        # Then PK
        valuelist.append(pkvalue)
        cursor = self.db.cursor()
        self.db_exec_with_cursor(
            cursor,
            get_sql_update_by_first_field(table, fieldlist, self.get_delims()),
            *valuelist
        )
916785
public String update(Object obj) {
    Class<?> clazz = obj.getClass();
    PersistMeta meta = EntityUtil.getMeta(clazz);
    StringBuilder setting = new StringBuilder(32);
    int i = 0;
    for (Map.Entry<String, Field> kv : meta.getColumns().entrySet()) {
      if (isNull(kv.getValue(), obj)) {
        continue;
      }

      if (i++ != 0) {
        setting.append(',');
      }

      setting.append('`').append(kv.getKey()).append('`').append("=#{").append(kv.getValue().getName()).append('}');
    }

    return new SQL().UPDATE(getTableName(meta, obj)).SET(setting.toString()).WHERE("id=#{id}").toString();
  }
1292652
private static void appendEscapedByte(StringBuilder builder, byte value) {
        builder.append('%');
        builder.append(HEX[(value >> 4) & 0x0f]);
        builder.append(HEX[value & 0x0f]);
    }
403883
public static String toSql(String name, String in) {
        if (in.indexOf('\\') != -1) {
            // has one or more escapes, un-escape and translate
            StringBuffer out = new StringBuffer();
            out.append('\'');
            boolean needLike = false;
            boolean needEscape = false;
            boolean lastWasEscape = false;
            for (int i = 0; i < in.length(); i++) {
                char c = in.charAt(i);
                if (!lastWasEscape && c == '\\') {
                    lastWasEscape = true;
                } else {
                    char nextChar = '!';
                    boolean useNextChar = false;
                    if (!lastWasEscape) {
                        if (c == '?') {
                            out.append('_');
                            needLike = true;
                        } else if (c == '*') {
                            out.append('%');
                            needLike = true;
                        } else {
                            nextChar = c;
                            useNextChar = true;
                        }
                    } else {
                        nextChar = c;
                        useNextChar = true;
                    }
                    if (useNextChar) {
                        if (nextChar == '\"') {
                            out.append("\\\"");
                            needEscape = true;
                        } else if (nextChar == '\'') {
                            out.append("\\\'");
                            needEscape = true;
                        } else if (nextChar == '%') {
                            out.append("\\%");
                            needEscape = true;
                        } else if (nextChar == '_') {
                            out.append("\\_");
                            needEscape = true;
                        } else {
                            out.append(nextChar);
                        }
                    }
                    lastWasEscape = false;
                }
            }
            out.append('\'');
            if (needLike) {
                out.insert(0, " LIKE ");
            } else {
                out.insert(0, " = ");
            }
            out.insert(0, name);
            if (needEscape) {
                out.insert(0, ' ');
            }
            return out.toString();
        } else {
            // no escapes, just translate if needed
            StringBuffer out = new StringBuffer();
            out.append('\'');
            boolean needLike = false;
            boolean needEscape = false;
            for (int i = 0; i < in.length(); i++) {
                char c = in.charAt(i);
                if (c == '?') {
                    out.append('_');
                    needLike = true;
                } else if (c == '*') {
                    out.append('%');
                    needLike = true;
                } else if (c == '\"') {
                    out.append("\\\"");
                    needEscape = true;
                } else if (c == '\'') {
                    out.append("\\\'");
                    needEscape = true;
                } else if (c == '%') {
                    out.append("\\%");
                    needEscape = true;
                } else if (c == '_') {
                    out.append("\\_");
                    needEscape = true;
                } else {
                    out.append(c);
                }
            }
            out.append('\'');
            if (needLike) {
                out.insert(0, " LIKE ");
            } else {
                out.insert(0, " = ");
            }
            out.insert(0, name);
            if (needEscape) {
                out.insert(0, ' ');
            }
            return out.toString();
        }
    }
1068339
function replacer() {
      // don't do any replacing if the user supplied no values
      if (!opts.values.length)
        return arguments[0];

      var ix = arguments.length > 3 ? parseInt(arguments[1], 10) : opts.value_ix++;
      var val = opts.values[ix - 1];
      if (_.isUndefined(val))
        throw new Error('Parameterized sql() (' + str + ') requires ' + ix + ' parameter(s) but only ' + opts.values.length + ' parameter(s) were supplied');
      if (_.isObject(sql) && !_.isArray(sql) && sql == null)
        return val.toString(opts);
      else
        return sql.convert(val);
    }
697855
private StringBuilder appendPagingSortSQL(final StringBuilder sql, final Post.Sort sort,final Paging paging) {

      if(paging.interval != null) {
         sql.append(" AND post_date");
         sql.append(paging.startIsOpen ? " >" : " >=");
         sql.append("?");

         sql.append(" AND post_date");
         sql.append(paging.endIsOpen ? " <" : " <=");
         sql.append("?");
      }

      switch(sort) {
         case ASC:
            sql.append(" ORDER BY post_date ASC");
            break;
         case DESC:
            sql.append(" ORDER BY post_date DESC");
            break;
         case ASC_MOD:
            sql.append(" ORDER BY post_modified ASC");
            break;
         case DESC_MOD:
            sql.append(" ORDER BY post_modified DESC");
            break;
         case ID_ASC:
            sql.append(" ORDER BY ID ASC");
            break;
         case ID_DESC:
            sql.append(" ORDER BY ID DESC");
            break;
         default:
            sql.append(" ORDER BY post_date DESC");
            break;
      }
      sql.append(" LIMIT ?,?");
      return sql;
   }
590276
public static String formatSQL(String sql) {
		if (sql == null || sql.length() == 0)
			return sql;
		StringBuilder sb = new StringBuilder();
		char[] chars = sql.toCharArray();
		boolean addedSpace = false;
		for (char c : chars) {
			if (isInvisibleChar(c)) {
				if (!addedSpace) {
					sb.append(" ");
					addedSpace = true;
				}
			} else {
				sb.append(c);
				addedSpace = false;
			}
		}
		sb.append(" ");
		return sb.toString();
	}