我已经开始迁移公地。Lang 2到commons.lang3.
根据https://commons.apache.org/proper/commons-lang/article3_0.html
StringEscapeUtils.escapeSql
这是一个误导的方法,只处理最简单的SQL情况。>因为SQL不是Lang的重点,所以维护这个方法没有意义。
理解它,但建议用什么代替它?
你能推荐一个类似于stringescapeutil .escapeSql的第三方吗?
From Javadocs:
目前,这种方法只能将单引号转换成双引号("McHale's Navy" => "McHale " s Navy")。
方法代码:
/**
675 * <p>Escapes the characters in a <code>String</code> to be suitable to pass to
676 * an SQL query.</p>
677 *
678 * <p>For example,
679 * <pre>statement.executeQuery("SELECT * FROM MOVIES WHERE TITLE='" +
680 * StringEscapeUtils.escapeSql("McHale's Navy") +
681 * "'");</pre>
682 * </p>
683 *
684 * <p>At present, this method only turns single-quotes into doubled single-quotes
685 * (<code>"McHale's Navy"</code> => <code>"McHale''s Navy"</code>). It does not
686 * handle the cases of percent (%) or underscore (_) for use in LIKE clauses.</p>
687 *
688 * see http://www.jguru.com/faq/view.jsp?EID=8881
689 * @param str the string to escape, may be null
690 * @return a new String, escaped for SQL, <code>null</code> if null string input
691 */
692 public static String escapeSql(String str) {
693 if (str == null) {
694 return null;
695 }
696 return StringUtils.replace(str, "'", "''");
697 }
所以你可以很容易地用一个简单的调用String#replace
来替换这个方法。
然而,该方法被删除是有原因的。它真的是半生不熟,我想不出一个好的理由为什么你会想要使用它。例如,要运行JDBC查询,您可以而且应该使用绑定变量,而不是尝试插入和转义字符串字面值。
OWASP提供了一个名为ESAPI的API,它提供了其中的一些功能,您可以查看它
在使用JDBC连接的情况下,准备一个带有如下参数的语句:
con.prepareStatement("INSERT INTO table1 VALUES (?,?)");
pstmt.setInt(1, 200);
pstmt.setString(2, "Julie");
pstmt.executeUpdate();
您不需要转义您在准备好的语句上使用函数插入的任何元素。这些将自动转义。
这个问题之前已经回答过了:Java -转义字符串防止SQL注入