Ejemplo n.º 1
0
  /**
   * Update the SQL string and replace the ? markers with parameter names eg @P0, @P1 etc.
   *
   * @param sql the SQL containing markers to substitute
   * @param list the parameter list
   * @return the modified SQL as a <code>String</code>
   */
  static String substituteParamMarkers(String sql, ParamInfo[] list) {
    // A parameter can have at most 8 characters: " @P" plus at most 4
    // digits plus " ". We subtract the "?" placeholder, that's at most
    // 7 extra characters needed for each parameter.
    char[] buf = new char[sql.length() + list.length * 7];
    int bufferPtr = 0; // Output buffer pointer
    int start = 0; // Input string pointer
    StringBuffer number = new StringBuffer(4);

    for (int i = 0; i < list.length; i++) {
      int pos = list[i].markerPos;

      if (pos > 0) {
        sql.getChars(start, pos, buf, bufferPtr);
        bufferPtr += (pos - start);
        start = pos + 1;

        // Append " @P"
        buf[bufferPtr++] = ' ';
        buf[bufferPtr++] = '@';
        buf[bufferPtr++] = 'P';

        // Append parameter number
        // Rather complicated, but it's the only way in which no
        // unnecessary objects are created
        number.setLength(0);
        number.append(i);
        number.getChars(0, number.length(), buf, bufferPtr);
        bufferPtr += number.length();

        // Append " "
        buf[bufferPtr++] = ' ';
      }
    }

    if (start < sql.length()) {
      sql.getChars(start, sql.length(), buf, bufferPtr);
      bufferPtr += (sql.length() - start);
    }

    return new String(buf, 0, bufferPtr);
  }