我已经开始将commons.lang 2迁移到commons.lang3。
根据0.html
StringEscapeUtils.escapeSql 这是一种误导的方法,只处理最简单的SQL案例。>因为SQL不是Lang的关注点,所以维护这个方法是没有意义的。
理解它,但是建议用什么代替它呢?
澄清
您能推荐一个执行类似于escapeSql的简单StringEscapeUtils.escapeSql的第三方吗?
发布于 2015-08-19 13:30:41
从Javadocs
目前,这种方法只将单引号转换为双单引号(“McHale的海军”=>“McHale的海军”)。
这是方法代码:
/**
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查询,您可以而且应该使用绑定变量,而不是尝试插值和转义字符串文本。
发布于 2016-06-27 07:01:26
OWASP有一个名为ESAPI的API,它提供了一些这些功能,您可以检查它。
发布于 2015-08-19 13:31:20
如果您正在使用JDBC连接,则使用如下参数准备语句:
con.prepareStatement("INSERT INTO table1 VALUES (?,?)");
pstmt.setInt(1, 200);
pstmt.setString(2, "Julie");
pstmt.executeUpdate();您不需要使用准备好的语句上的函数转义插入的任何元素。这些都是自动转义的。
这一点以前已经在:Java -转义字符串以防止SQL注入中得到了回答。
https://stackoverflow.com/questions/32096614
复制相似问题