从commons.lang迁移StringEscapeUtils.escapeSql

Mic*_*ael 9 java apache-commons-lang

我已经开始将commons.lang 2迁移到commons.lang3.

根据 https://commons.apache.org/proper/commons-lang/article3_0.html

StringEscapeUtils.escapeSql

这是一种误导性的方法,只处理最简单的SQL案例.>由于SQL不是Lang的重点,因此维护此方法没有意义.

理解它,但建议使用什么而不是它?

澄清

你能推荐第三方执行类似于StringEscapeUtils.escapeSql的简单escapeSql吗?

Thi*_*ilo 15

来自Javadocs:

目前,这种方法只能将单引号变为双引号("麦克海尔海军"="麦克海尔海军").

这是方法代码:

  /**
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        }
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过简单的调用轻松替换该方法String#replace.

但是,有一个原因是该方法被删除.这真是半生不熟,我想不出你想要使用它的一个很好的理由.例如,要运行JDBC查询,您可以而且应该使用绑定变量而不是尝试插入和转义字符串文字.

  • 实际上确实存在一个用例:转义 SQL 语句中不能通过绑定变量进行参数化的部分。例如表名本身:http://stackoverflow.com/q/1208442/274677 (2认同)