java单引号替换,Java用'(撇号/单引号)和\(反斜杠)替换问题

博客讨论了在处理包含单引号的查询字符串时遇到的问题,尝试使用replace方法替换单引号为反斜杠加单引号但未成功。解决方案提到,对于URL编码,应该使用URLEncoder.encode()方法,并提醒注意SQL注入风险,建议使用PreparedStatement。
摘要由CSDN通过智能技术生成

I seem to be having issues. I have a query string that has values that can contain single quotes. This will break the query string. So I was trying to do a replace to change ' to \'.

Here is a sample code:

"This is' it".replace("'", "\'");

The output for this is still:

"This is' it".

It thinks I am just doing an escape character for the quote.

So I tried these two pieces of code:

"This is' it".replace("'", "\\'"); // \\ for the backslash, and a ' char

"This is' it".replace("'", "\\\'"); // \\ for the backslash, and \' for the ' char

Both of the above STILL results in the same output:

"This is' it"

I can only seem to get this to actually spit out a slash with:

"This is' it".replace("'", "\\\\'");

Which results in:

"This is\\' it"

Any suggestions? I just want to replace a ' with \'.

It doesn't seem like it should be that difficult.

解决方案

First of all, if you are trying to encode apostophes for querystrings, they need to be URLEncoded, not escaped with a leading backslash. For that use URLEncoder.encode(String, String) (BTW: the second argument should always be "UTF-8"). Secondly, if you want to replace all instances of apostophe with backslash apostrophe, you must escape the backslash in your string expression with a leading backslash. Like this:

"This is' it".replace("'", "\\'");

Edit:

I see now that you are probably trying to dynamically build a SQL statement. Do not do it this way. Your code will be susceptible to SQL injection attacks. Instead use a PreparedStatement.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值