Java equivalent for PHP's mysql_real_escape_string()

后端 未结 7 680
温柔的废话
温柔的废话 2021-01-11 10:17

Is there a Java equivalent to PHP\'s mysql_real_escape_string() ?

This is to escape SQL injection attempts before passing them to Statement.execute().

I know

7条回答
  •  暖寄归人
    2021-01-11 10:37

    According to Daniel Schneller, there is no standard way to handle PHP's mysql_real_escape_string() in Java What I did was to chain replaceAll method to handle every aspect that may be necessary to avoid any exception. Here is my sample code:

    public void saveExtractedText(String group,String content) { try { content = content.replaceAll("\\", "\\\\") .replaceAll("\n","\\n") .replaceAll("\r", "\\r") .replaceAll("\t", "\\t") .replaceAll("\00", "\\0") .replaceAll("'", "\\'") .replaceAll("\\"", "\\\"");

            state.execute("insert into extractiontext(extractedtext,extractedgroup) values('"+content+"','"+group+"')");
        } catch (Exception e) {
            e.printStackTrace();
    
        }
    

提交回复
热议问题