最近处理通过JDBC导出备份mysql数据库,中间历经波折踩了不少坑,不过也收获颇多,在此分享下。

MySQL转义符

  • '0':ASCII 0 (NUL)符;
  • 'n':换行符;
  • 'r':回车符;
  • '\':反斜杠(“”)符;
  • ''':单引号(“'”)符;
  • '"':双引号(“"”)符

判断是否需要转义方法:isNeedEscape

先判断字符串是否含有特殊符号,方法:isNeedEscape:

/**
 * 判断内容是否需要进行转义
 * @param x
 * @return
 */
public static boolean isNeedEscape(String x) {
    boolean needsHexEscape = false;
    if(StringUtils.isBlank(x)) {
        return needsHexEscape;
    }
    int stringLength = x.length();
    int i = 0;
    do
    {
        if(i >= stringLength)
            break;
        char c = x.charAt(i);
        switch(c)
        {
        case 0: // '\0'
            needsHexEscape = true;
            break;

        case 10: // '\n'
            needsHexEscape = true;
            break;

        case 13: // '\r'
            needsHexEscape = true;
            break;

        case 92: // '\\'
            needsHexEscape = true;
            break;

        case 39: // '\''
            needsHexEscape = true;
            break;

        case 34: // '"'
            needsHexEscape = true;
            break;

        case 26: // '\032'
            needsHexEscape = true;
            break;
        }
        if(needsHexEscape)
            break;
        i++;
    } while(true);
    return needsHexEscape;
}

转义方法:escapeString

/**
 * 对mysql字符进行转义
 * @param x
 * @return
 */
public static String escapeString(String x) {
    if(Strings.isBlank(x)) {
        return x;
    }
    if(!isNeedEscape(x)) {
        return x;
    }
    int stringLength = x.length();
    String parameterAsString = x;
    StringBuffer buf = new StringBuffer((int)((double)x.length() * 1.1000000000000001D));
    // 可以指定结果前后追加单引号:'
    //buf.append('\'');
    for(int i = 0; i < stringLength; i++)
    {
        char c = x.charAt(i);
        switch(c)
        {
        default:
            break;

        case 0: // '\0'
            buf.append('\\');
            buf.append('0');
            continue;

        case 10: // '\n'
            buf.append('\\');
            buf.append('n');
            continue;

        case 13: // '\r'
            buf.append('\\');
            buf.append('r');
            continue;

        case 92: // '\\'
            buf.append('\\');
            buf.append('\\');
            continue;

        case 39: // '\''
            buf.append('\\');
            buf.append('\'');
            continue;

        case 34: // '"'
            buf.append('\\');
            buf.append('"');
            continue;

        case 26: // '\032'
            buf.append('\\');
            buf.append('Z');
            continue;

        }
        buf.append(c);
    }
    // 可以指定结果前后追加单引号:'
    //buf.append('\'');
    parameterAsString = buf.toString();
    return parameterAsString;
}

参考文章:

标签: mysql, java

添加新评论