mysql 换行符 转义_MySQL字符转义涉及的问题及解决

本文介绍了在处理MySQL数据库时遇到的字符转义问题,特别是与换行符相关的处理。分享了如何判断字符串是否需要转义的`isNeedEscape`方法,以及实现字符串转义的`escapeString`方法,确保JDBC导出备份的正确性。内容包括对NUL、换行符、回车符、反斜杠等特殊字符的转义规则和处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近处理通过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;

}

参考文章:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值